python - 我们如何打印 Python 文本文件中出现单词的行号?

标签 python python-3.x

我需要它来打印文本文件中相应的行号。

def index (filename, lst):
    infile = open('raven.txt', 'r')
    lines =  infile.readlines()
    words = []
    dic = {}

    for line in lines:
        line_words = line.split(' ')
        words.append(line_words)
    for i in range(len(words)):
        for j in range(len(words[i])):
            if words[i][j] in lst:

                dic[words[i][j]] = i

    return dic

结果:

In: index('raven.txt',['raven', 'mortal', 'dying', 'ghost', 'ghastly', 'evil', 'demon'])

Out: {'dying': 8, 'mortal': 29, 'raven': 77, 'ghost': 8}

(上面的文字出现在几行中,但它只打印一行,有些则不打印任何内容 此外,它不计算文本文件中的空行。所以 8 实际上应该是 9,因为有一个空行不计算在内。)

请告诉我如何解决这个问题。

最佳答案

def index (filename, lst):

    infile = open('raven.txt', 'r')
    lines =  infile.readlines()
    words = []
    dic = {}

    for line in lines:
        line_words = line.split(' ')
        words.append(line_words)
    for i in range(len(words)):
        for j in range(len(words[i])):
            if words[i][j] in lst:
                if words[i][j] not in dic.keys():
                    dic[words[i][j]] = set()
                dic[words[i][j]].add(i + 1) #range starts from 0
    return dic

如果单词在同一行中多次出现,则使用集合而不是列表很有用。

关于python - 我们如何打印 Python 文本文件中出现单词的行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33741373/

相关文章:

python - 安装 Ta-lib 会产生 gcc 错误

Python urllib 无法打开 localhost

python - 如何在Python中根据groupby()输出执行累积和

python - 如何让python重新将连续匹配模式选项视为模式的单次出现?

python - Azure Linux Web 应用程序(startup.sh : not found)

python - 集合和 View 之间的区别

python - 如何从文本文件中去除标点符号

python - 如何将从 Chrome 复制的 css 选择器路径转换为 ​​beautifulsoup 对象?

python - 使用 for 循环限制程序的线程

python - 如何修复 "latin-1 codec can' t 在请求中的位置编码字符