在Python NLTK中使用一致性返回字典中找到的键的值
我想使用concordance查找文本中单词或短语的实例,然后在字典中查找找到的单词/短语并返回相应的值。这是我到目前为止的代码在Python NLTK中使用一致性返回字典中找到的键的值,python,dictionary,nltk,Python,Dictionary,Nltk,我想使用concordance查找文本中单词或短语的实例,然后在字典中查找找到的单词/短语并返回相应的值。这是我到目前为止的代码 from __future__ import division import nltk, re, pprint OutFileName = "shark_uri.txt" OutFile = open(OutFileName, 'w') book1 = open('shark_test.txt', 'rU').read() token1 = nltk.word_to
from __future__ import division
import nltk, re, pprint
OutFileName = "shark_uri.txt"
OutFile = open(OutFileName, 'w')
book1 = open('shark_test.txt', 'rU').read()
token1 = nltk.word_tokenize(book1)
text1 = nltk.Text(token1)
LineNumber = 0
for k, v in bio_dict.iteritems():
text1.concordance(k)
#if k is found then print v, else go on to next k
if k #is found:
OutFile.write(v)
OutFile.write('\n')
LineNumber += 1
else
LineNumber += 1
OutFile.close()
这段代码应该在shark_test.txt文件中读取一段关于鲨鱼的内容。bio_dict包含这样的键值对
'ovoviviparous':'http://dbpedia.org/resource/Ovoviviparity',
'predator':'http://dbpedia.org/resource/Predation',
关键字表示程序正在查找的单词或短语。该值是对应于单词/短语的DBpedia URI。其思想是,当在文本中找到类似“捕食者”的单词时,程序将返回DBpedia URI以供捕食。
我得到了很多奇怪的结果,我想这是因为我需要告诉程序,如果发现k返回v,那么就转到下一个k。我已经在上面的代码块中放置了一个占位符。我不太知道如何用Python来表达这一点。如果k==真,会是这样吗?
如果没有这个条件,它似乎只是在通过字典打印所有值,而不管是否找到键。有什么建议吗?提前感谢。您的代码现在的工作方式是迭代
bio_dict
字典中的所有键、值对,然后使用concordance
打印text1
中存在k
的行。这里需要注意的重要一点是,使用一致性不会返回任何内容,而只是打印。因此,即使您尝试使用返回值(实际上在代码中没有),您也不能。当您编写if k:
时,这将始终是True
——假设您的键是非空字符串(没有一个键的计算结果为False
)
如果我正确理解了您的问题,您真的不应该使用concordance
。相反,可以这样做:
for word in token1: # Go through every word in your text
if word in bio_dict: # Check if the word is in the dict
OutFile.write(bio_dict[word]+'\n') # Output the value to your file
此外,您的
LineNumber
计数器实际上并不计算您想要的内容,因为您正在一次读取输入文件,并在token1
中标记整个内容。但是,由于您实际上没有使用LineNumber
,因此可以删除该变量并仍然获得所需的输出。我通过这段代码获得了所需的内容
from __future__ import division
import urllib
import re, pprint, time
in_file_name = "shark_id.txt"
in_file = open(in_file_name, 'r')
out_file_name = "shark_uri.txt"
out_file = open(out_file_name, 'w')
for line in in_file:
line = line.strip()
address = 'http://eol.org/api/data_objects/1.0/' + line + '.xml'
web_content = urllib.urlopen(address)
results = web_content.read().lower()
temp_file_name = "Temp_file.xml"
temp_file = open(temp_file_name, 'w')
temp_file.write(results)
temp_file.close()
print line
print len(results)
temp_file = open('Temp_file.xml')
data = temp_file.read()
temp_file.close()
for k, v in bio_dict.iteritems():
if k in data:
out_file.write(line + ',')
out_file.write(k + ',')
out_file.write(v)
out_file.write('\n')
time.sleep(.5)
in_file.close()
out_file.close()