我的代码的目标是将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”的出现次数。我希望代码返回:
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)]
因此,不是在f中的行,你会在lineList中找到行:等等