我正在尝试处理一段处理文件输入/输出的代码。程序提示输入文件名,打开它(如果存在)并读取它,一次一行。它将每一行拆分为更大 wordList 的单独子列表。所有这一切都很好。
我遇到问题的部分是,我应该跟踪每个单词在文件/列表中出现的次数。此外,该列表应该是唯一的,因此 count 功能对我来说真的不起作用。我有一段代码似乎应该对我有用,但事实并非如此。
aFile = theFile.readline()
while aFile != '':
aFile = aFile.split()
for i in aFile:
try:
isInt = float(i)
numList.append(i)
except ValueError:
if not wordList:
tempList = []
tempList.append(i)
tempList.append(wordCount)
wordList.append(tempList)
else:
for n in wordList:
try:
if i in n:
print ('You should see this')
wordIndex = wordList.index(i)
wordList[wordIndex][1] +=1
except ValueError:
tempList = []
tempList.append(i)
tempList.append(wordCount)
wordList.append(tempList)
这只是与读取输入文件有关的块,将其拆分并将其放入列表中 - 或至少尝试这样做。截至目前,运行代码会导致无限循环,并在其中无限打印“你应该看到这个”。
如果我进行第二次尝试:除了循环,它不会再给我一个无限循环,但是当在 wordList 中找不到文件中的第二个单词时它确实给了我一个 ValueError (因为它不应该,因为之前只输入了一个词)。
谁能看到我做错了什么?如果需要,我可以发布其余的代码。