首页 > 解决方案 > 在列表中读取和输出使用它的行的脚本

问题描述

我正在使用带有“一些文本”的 .py 文件,然后使用我的代码生成一个字典,其中包含一个单词在文本中使用了多少次。

{}    
for x in text:       

        x = x.lower()    

但是,我正在寻找一种方法来执行使用元素(即 x、单词、isalpha 等)的行的列表,我不想包含forif。要打印出上面的脚本,我使用

filename = 'test.py'

        print(n, line, end='')

这就是我想要的最终输出:

1
2 words = {} 
          words[x] += 1

10 print(words)


x               
words         ]

lower        [3]

我假设我可以使用re Module,但是,我会很感激提示

标签: pythonregexlistdictionary

解决方案


如果我清楚地了解您要执行的操作,您可以使用以下代码:

import re
from keyword import kwlist


i = 1
map = {}
with open("script.py", "r") as file:
    while True:
        line = file.readline()
        if not line: break

        # iterates over each real word on each line
        for x in re.split(r'[^\w]', line):
            # adds the world to the map only if it is not '', nor a number, nor a python keyword
            if x and not x.isdigit() and x not in kwlist:
                if not x in map: map[x] = [i]
                else: map[x].append(i)
        i += 1


# displays the map
for key in map:
    print(key, map[key], sep='\t\t')

这将产生:

words       [2, 6, 7, 9, 10]
x           [3, 4, 5, 5, 6, 7, 9]
text        [3]
isalpha     [4]
lower       [5]
print       [10]

推荐阅读