python - 在列表中读取和输出使用它的行的脚本
问题描述
我正在使用带有“一些文本”的 .py 文件,然后使用我的代码生成一个字典,其中包含一个单词在文本中使用了多少次。
{}
for x in text:
x = x.lower()
但是,我正在寻找一种方法来执行使用元素(即 x、单词、isalpha 等)的行的列表,我不想包含for
等if
。要打印出上面的脚本,我使用
filename = 'test.py'
print(n, line, end='')
这就是我想要的最终输出:
1
2 words = {}
words[x] += 1
10 print(words)
x
words ]
lower [3]
我假设我可以使用re Module,但是,我会很感激提示
解决方案
如果我清楚地了解您要执行的操作,您可以使用以下代码:
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]
推荐阅读
- ios - 如何使用 SceneKit iOS 将背面图像添加为纹理
- ios - Swift:在 2D 中旋转点
- android - 应用在实施播放服务广告时不显示
- python - 如何简化代码以检查 pandas 中的范围
- jquery - jQuery hover() 函数为 div 内的所有 'a' 标签着色,而不是只悬停在上面的标签
- css - 为什么两个浮动 div 之一被推到下一行?
- python - 如何调用python中特定函数从对话框中选择的图像
- listview - Nativescript 后退结果页面为空白
- reactjs - 动态api变化
- python - 在flask路由中添加带有函数返回值的硬编码字符串,以在调用api时显示带有返回值的硬编码字符串