【问题标题】:How do I get the specific number of a word in a txt file?如何获取txt文件中某个单词的具体编号?
【发布时间】: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


【解决方案1】:

如果你想找到单词中第一次出现的单词,只需使用

wordIndex = words.index(w) if w in words else None

并且在所有情况下使用

wordIndexes = [i for i,x in enumerate(words) if x==word] 

(取自Python: Find in list) 但请注意:如果您的文本是“cat, dog, mouse”,您的代码将找不到“cat”或“dog”的索引。因为 "cat, dog, mouse".split() 返回 ['cat,', 'dog,', 'mouse'],而 'cat' 不是 'cat'。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多