【问题标题】:Print Word & Line Number Where Word Occurs in File Python打印文件 Python 中出现 Word 的单词和行号
【发布时间】:2016-09-09 01:56:12
【问题描述】:

我正在尝试打印 Python 文件中出现该单词的单词和行号。目前我得到了第二个单词的正确数字,但我查找的第一个单词没有打印正确的行号。 必须遍历 infile,使用字典存储行号,删除新行字符,删除任何标点符号并在提取数字时跳过空白行。我需要添加一个实际上是列表的值,以便如果单词包含在多行中,我可以将行号添加到列表中。

调整后的代码:

def index(f,wordf):

    infile = open(filename, 'r')
    dct = {}
    count = 0
    for line in infile:
        count += 1
        newLine = line.replace('\n', ' ')
        if newLine == ' ':
            continue
        for word in wordf:
            if word in split_line:
                if word in dct:
                    dct[word] += 1
                else:
                    dct[word] = 1

    for word in word_list:
        print('{:12} {},'.format(word,dct[word]))
    infile.close()       

电流输出:

>>> index('leaves.txt',['cedars','countenance'])
pines        [9469, 9835, 10848, 10883],
counter      [792, 2092, 2374],

期望的输出:

>>> index2('f.txt',['pines','counter','venison'])
pines       [530, 9469, 9835, 10848, 10883]
counter     [792, 2092, 2374]

【问题讨论】:

  • 我想要的输入被截断以便于理解。但是,我刚刚注意到当前输出实际上是在提取文件中出现单词的实例。这意味着,我要么没有正确递增或将行号添加到字典中。
  • 第三个循环你还是要把'word'改成'word2',而且关联的地方用'word2',不然肯定不行,看我下面的帖子跨度>
  • 您是否在 IDE(或其他可执行变体)中运行它?在这种情况下,如果您将 word 更改为 word 2 并不重要,并且当您使用代码的最后一个变体时,您会得到一个错误。就像我说的最后一个代码,无论如何,它不会提取行号,它会提取其他内容。
  • for word2 in split_line: if word2 == word: 这是你需要的部分。如果没有比较,您当前的代码将无法使用“word2”,并且在进行比较时您没有“word2”
  • 当我在第三个 for 循环中调整代码以反映 word2 时,代码不会打印出单词的行号实例。

标签: python-3.x


【解决方案1】:

您的文件的设置方式有些模糊,但我认为它可以理解。 试试这个:

import numpy as np # add this import
...

    for word in word_f:
        if word in split_line:

            np_array = np.array(split_line)
            item_index_list = np.where(np_array == word)

            dct[word] = item_index_list # note, you might want the 'index + 1' instead of the 'index'

for word in word_f:
    print('{:12} {},'.format(word,dct[word]))
...

顺便说一句,据我所知,您没有使用“增量”变量。

我认为这会起作用,如果不起作用,请告诉我,我会修复它

【讨论】:

  • 感谢您的帮助!你有什么想法在没有任何进口的情况下完成它吗?我真的想了解如何遍历文件并从根本上向字典添加增量。现在,我确实认为您指出我不使用增量变量可能是我的问题之一,但我认为另一个问题始于第二个 for 循环,我认为这就是我的程序计算实例的原因出现单词而不是行号。
  • 是的,可以,给我一点,我会发布另一个解决方案
  • 感谢您的帮助!!
  • 对不起,我没有解决您的第一个声明。文件的设置方式就像一个 .txt 的诗歌文件。所以第一行是诗名,\n,作者,\n,\n,然后是诗(每一节都在各自的行)。
  • 文本中真的有'\n'吗?换句话说,“诗名,\n,作者,\n,\n”在同一行吗?
【解决方案2】:

根据请求,我在不导入另一个库的情况下做了一个额外的答案(我认为可行)

def index2(f,word_f):

    infile = open(f, 'r')
    dct = {}
    # deleted line
    for line in infile:
        newLine = line.replace('\n', ' ')
        if newLine == ' ':
            continue
        # deleted line
        newLine2 = removePunctuation(newLine)
        split_line = newLine2.split()
        for word in word_f:
            count = 0 # you might want to start at 1 instead, if you're going for 'word number'
            # important note: you need to have 'word2', not 'word' here, and on the next line
            for word2 in split_line: # changed to looping through data
                if word2 == word:                    
                    if word2 in dct:
                        temp = dct[word]
                        temp.append(count)
                        dct[word] = temp
                    else:
                        temp = []
                        temp.append(count)
                        dct[word] = temp
                count += 1
    for word in word_f:
        print('{:12} {},'.format(word,dct[word]))
    infile.close()    

请注意,如果传入的单词不在文件中,我认为这段代码不会处理。我对您从中获取的文件不肯定,所以我不能确定,但​​我认为如果您传入文件中不存在的单词,它会出现段错误。

【讨论】:

  • 有一种情况是传入的单词不会在文件中。您希望我修复可能发生的错误吗?
  • 输出很奇怪。它似乎没有拉出单词出现的行号。我得到了第一个单词输入“[11, 11, 11, 5, 5, 5, 8, 8, 8, 4, 4, 4, 3, 3, 3, 5, 5, 5, 7, 7, 7 ]" 我不确定那是什么,我得调查一下。
  • 你能提供一个小输入文件的例子吗
  • 哎呀,刚刚在我的帖子中看到一个错误...我刚刚编辑它,我使用了两次相同的“word”变量,现在第二个是“word2”,还有一个额外的比较
  • 很奇怪!您上面的代码仍然没有给出行号。现在的输出是 [11, 5, 8, 4, 3, 5, 7],也许我们正在考虑做不同的事情?我调整了您的代码以提取出现单词的文件中的行号,但它是重复的行号。让我发一下
【解决方案3】:

注意:我从我的另一篇帖子中获取了此代码以查看它是否有效,并且似乎有效

def index2():

    word_list = ["work", "many", "lots", "words"]
    infile = ["lots of words","many many work words","how come this picture lots work","poem poem more words that rhyme"]
    dct = {}
    # deleted line
    for line in infile:
        newLine = line.replace('\n', ' ') # shouldn't do anything, because I have no newlines
        if newLine == ' ':
            continue
        # deleted line
        newLine2 = newLine # ignoring punctuation
        split_line = newLine2.split()
        for word in word_list:
            count = 0 # you might want to start at 1 instead, if you're going for 'word number'
            # important note: you need to have 'word2', not 'word' here, and on the next line
            for word2 in split_line: # changed to looping through data
                if word2 == word:
                    if word2 in dct:
                        temp = dct[word]
                        temp.append(count)
                        dct[word] = temp
                    else:
                        temp = []
                        temp.append(count)
                        dct[word] = temp
                count += 1
    for word in word_list:
        print('{:12} {}'.format(word, ", ".join(map(str, dct[word])))) # edited output so it's comma separated list without a trailing comma


def main():
    index2()


if __name__ == "__main__":main()

和输出:

work         2, 5
many         0, 1
lots         0, 4
words        2, 3, 3

及解释:

infile = [
"lots of words",                        # lots at index 0, words at index 2
"many many work words",                 # many at index 0, many at index 1, work at index 2, words at index 3
"how come this picture lots work",      # lots at index 4, work at index 5
"poem poem more words that rhyme"       # words at index 3
]

当它们按该顺序附加时,它们会得到正确的单词放置位置

【讨论】:

  • 如果你想要别的东西,我不确定是什么
  • 我知道发生了什么!谢谢你的解释。我真正要查找的是单词出现的行号,而不是单词在该行中出现的索引。把它想象成书后的索引。
  • 你所要做的就是将'count = 0'行移到第一个for循环之前,并且count += 1移出一个for循环(在第一个和第二个之间)。这应该会给你行号
  • 如果你只想要 'word number' 如果你只是将 'count = 0' 移到第一个 for 循环之外,那么它应该指示文件中的单词数,直到单词出现
  • 实际上我刚刚发布的“字数”帖子有点不对劲……编辑太晚了……如果你只想要“字数”,只要将“count = 0”移到外面第一个 for 循环,然后 'count += 1' 的位置必须稍微改变一下,因为它在一个循环中,对传入的单词进行计数。让我知道这是否是你想要的,我应该能够帮助,但可能要等到明天
【解决方案4】:

我最大的错误是我没有正确地将行号添加到计数器中。我完全使用了错误的调用,并且没有做任何事情来增加行号,因为在文件中找到了这个词。正确的格式是 dct[word] += [count] 而不是 dct[word] += 1

def index(filename,word_list):

    infile = open(filename, 'r')
    dct = {}
    count = 0
    for line in infile:
        count += 1
        newLine = line.replace('\n', ' ')
        if newLine == ' ':
            continue
        newLine2 = removePunctuation(newLine)
        split_line = newLine2.split()
        for word in word_list:
            if word in split_line:
                if word in dct:
                    dct[word] += [count]
                else:
                    dct[word] = [count]
    for word in word_list:
        print('{:12} {}'.format(word,dct[word]))
    infile.close()

【讨论】:

    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 2021-01-31
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2017-02-15
    • 1970-01-01
    相关资源
    最近更新 更多