首页 > 解决方案 > 难以遍历字典以在 .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()

标签: pythonopenpyxl

解决方案


问题是您正在读取文件一次,然后您的指针位于文件末尾,所以下次您来到该部分

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


推荐阅读