【发布时间】:2019-07-16 14:27:22
【问题描述】:
我正在尝试查找 TXT 文件中何时使用某些特定单词之一,然后计算该单词在文件中的编号。我的代码返回了一些但不是所有单词的数字,我不知道为什么。
我的代码现在用一个计数器逐个字地遍历文件,如果该字词与我想要的字词之一匹配,则返回数字。
def wordnumber(file, filewrite, word1, word2, word3):
import os
wordlist = [word1, word2, word3]
infile = open(file, 'r')
g = open(filewrite, 'w')
g.write("start")
g.write(os.linesep)
lines = infile.read().splitlines()
infile.close()
wordsString = ' '.join(lines)
words = wordsString.split()
n = 1
for w in words:
if w in wordlist:
g.write(str(n))
g.write(os.linesep)
n = n+1
这有时有效,但对于某些文本文件,它只返回一些数字而将其他数字留空。
【问题讨论】:
-
@max 如果你的最后一行是
g.close(),在循环之后,这能解决问题吗? -
不,它仍然没有计算所有的单词
-
最好使用
with open(filename, 'r') as infile: infile_lines = infile.readlines()在this page上检查with statement
标签: python