【发布时间】:2015-08-14 12:58:26
【问题描述】:
我正在尝试解析 .CSV 文件中的一些字典,使用单独的 .txt 文件中的两个列表,以便脚本知道它在寻找什么。我们的想法是在 .CSV 文件中找到与 Word 和 IDNumber 都匹配的行,然后在匹配时提取第三个变量。但是,代码运行速度非常慢。有什么想法可以提高效率吗?
import csv
IDNumberList_filename = 'IDs.txt'
WordsOfInterest_filename = 'dictionary_WordsOfInterest.txt'
Dictionary_filename = 'dictionary_individualwords.csv'
WordsOfInterest_ReadIn = open(WordsOfInterest_filename).read().split('\n')
#IDNumberListtoRead = open(IDNumberList_filename).read().split('\n')
for CurrentIDNumber in open(IDNumberList_filename).readlines():
for CurrentWord in open(WordsOfInterest_filename).readlines():
FoundCurrent = 0
with open(Dictionary_filename, newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if ((row['IDNumber'] == CurrentIDNumber) and (row['Word'] == CurrentWord)):
FoundCurrent = 1
CurrentProportion= row['CurrentProportion']
if FoundCurrent == 0:
CurrentProportion=0
else:
CurrentProportion=1
print('found')
【问题讨论】:
-
您能否提供一个示例说明您希望如何显示输出?
-
这段代码的复杂度为 O(mn),其中
m和n是各自文件中单词和 id 的计数。难怪它真的很慢。它真的需要检查 ID 和 word 的所有可能组合吗? -
CurrentProportion= row['CurrentProportion']在使用前设置为 0 或 1 有什么意义? -
dictionary_WordsOfInterest.txt和IDs.txt有多大?你能一口气读完吗?如果是这样,我建议将它们存储在set()中并使用运算符in。 (即a = set([1,2,3]); 1 in a)。在一个集合中的平均搜索时间是 O(1)。 -
谢谢... CurrentProportion = 1 目前只是一个占位符。我将 CurrentProportion 设置为零虽然是因为我想要输出。如果文件中没有Proportion(因为PID和CurrentWord不匹配),那么我想将它设置为0。
标签: python list csv python-3.x