python - 难以遍历字典以在 .txt 中搜索字典中的值
问题描述
我的代码的目标是将 excel 电子表格转换为字典 + 使用该字典在 .txt 文件中搜索字符串 + 打印出每个字符串在文本中使用的次数的计数。我遇到的问题是遍历 Dictionary 并获取所有 Dictionary 值的计数。
我尝试使用 for 循环枚举和迭代值,但我最终仍然只获得“Carla”的计数,而不是获得所有 Dictionary 项目的计数。
Dict = {}
for row in range(1, dictionary.max_row+1):
for col in range(1, 2):
cell_value = dictionary.cell(row=row, column=col).value
Dict[cell_value] = dictionary.cell(row=row, column=1).value
def searchtxt():
count = 0
with open('26440384.txt', 'r') as f:
for key in Dict.values():
print(key)
for line in f:
count += line.count(str(key))
print(count)
count = 0
searchtxt()
回报:
Carla
6
God
radiation
我得到了打印出字典所有项目的代码,但它只计算文本中出现“Carla”的次数。我希望代码返回这个:
Carla
6
God
4
radiation
3
s/p Klaas 的编辑:
def searchtxt():
count = 0
with open('26440384.txt', 'r') as f:
for key in Dict.values():
print(key)
lineList = [line.rstrip('\n') for line in open('26440384.txt', 'r')]
for key in lineList:
count += lineList.count(str(key))
print(count)
count = 0
searchtxt()
回报:
Carla
1
God
1
radiation
1
解决方案:
def searchtxt():
count = 0
with open('26440384.txt', 'r') as f:
for key in Dict.values():
print(key)
for line in f:
count += line.count(str(key))
print(count)
count = 0
f.seek(0)
searchtxt()
解决方案
问题是您正在读取文件一次,然后您的指针位于文件末尾,所以下次您来到该部分
for line in f:
count += line.count(str(key))
print(count)
count = 0
文件中没有更多行可以读取,因为您已经在末尾了。如果文件不是太大(或者你不担心内存),我会先将文件读入列表,然后遍历该列表
lineList = [line. rstrip('\n') for line in open(fileName)]
因此,而不是 for line in f 你会去 line in lineList: etc
推荐阅读
- asp.net-core - Blazor:“无法读取未定义的属性‘parentNode’”
- python-3.x - 如何在odoo中更改表单视图和树视图中字段的格式?
- kubernetes - Kapp 在 gitlab-ci 中没有显示颜色
- javascript - 如果条形图的颜色高于混合图表chart.js中的平均分数,如何更改它的颜色
- sql - 如何在 XML Path 查询 SQL 中使用标量变量?
- sql - 整数值无效(无法将值存储到数据库中)
- android - Flutter app调试问题,连接服务协议报错:无法连接到http://127.0.0.1:5016
- javascript - 删除内容时如何为可折叠的内部高度设置动画
- assembly - 在汇编中实现算术
- powershell - Powershell - 虚拟机 CPU 和主机 CPU 的总和