我试着在一个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
这种方法有时有效,但对于某些文本文件,它只返回部分数字,而将其他数字留空。你知道吗
如果你想在你的词中找到这个词的第一个出现,就用
对于所有发生的情况,请使用
(摘自Python: Find in list) 但要注意:如果您的文本是“猫,狗,鼠标”,您的代码将找不到“猫”或“狗”的索引。因为“cat,dog,mouse”.split()返回['cat','dog','mouse'],而'cat'不是'cat'。你知道吗
相关问题 更多 >
编程相关推荐