难于遍历字典以在.txt中搜索字典中的值

时间:2019-04-18 15:57:45

标签: python openpyxl

我的代码的目标是将excel电子表格转换为字典+使用该字典在.txt文件中搜索字符串+打印每个字符串在文本中使用次数的计数。我遇到的麻烦是遍历字典并获取所有字典值的计数。

我尝试使用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
6
God
4
radiation
3

s / p克拉斯的修改

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()

1 个答案:

答案 0 :(得分:0)

问题在于,您只读取了一次文件,然后指针就位于文件的末尾,因此下一次您进入该部分

for line in f:
            count += line.count(str(key))
            print(count)
            count = 0

文件已经没有最后几行可供阅读了。 如果文件不太大(或者您不担心内存),我会先将文件读入列表,然后循环浏览该列表

lineList = [line. rstrip('\n') for line in open(fileName)]

因此,与其在f中的行,不如在lineList中的行:etc