继前面的post之后,我编写了一些Python代码来计算大量文本文件中某些短语(包含在“word_list”变量中,列出了三个示例,但还有更多示例)的出现频率。我在下面编写的代码要求我获取列表中的每个元素,并将其插入字符串中,以便与每个文本文件进行比较。然而,当前代码只是将列表中最后一个短语的频率写入电子表格中的相关列,而不是全部写入。这只是一个缩进问题,没有将writerow放在正确的位置,还是代码中存在逻辑缺陷。还有什么方法可以避免使用列表到字符串赋值,以便将短语与文本文件中的短语进行比较
word_list = ['in the event of', 'frankly speaking', 'on the other hand']
S = {}
p = 0
k = 0
with open(file_path, 'w+', newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(["Fohone-K"] + word_list)
for filename in glob.glob(os.path.join(path, '*.txt')):
if filename.endswith('.txt'):
f = open(filename)
Fohone-K = filename[8:]
data = f.read()
# new code section from scratch file
l = len(word_list)
for s in range(l):
phrase = word_list[s]
S = data.count((phrase))
if S:
#k = k + 1
print("'{}' match".format(Fohone-K), S)
else:
print("'{} no match".format(Fohone-K))
print("\n")
# for m in word_list:
if S >= 0:
print([Fohone-K] + [S])
writer.writerow([Fohone-K] + [S])
当前的输出如下所示
当它需要看起来像这样的时候
你可能想做这样的事情:
关键问题是在每一行上写入
S
,这只包含一个计数。这里通过编写一组完整的匹配项来解决这个问题相关问题 更多 >
编程相关推荐