【问题标题】:Python 3.6.1: Code does not execute after a for loopPython 3.6.1:代码在 for 循环后不执行
【发布时间】:2017-07-14 23:28:12
【问题描述】:

我一直在学习 Python,我想编写一个脚本来计算文本中的字符数并计算它们的相对频率。但首先,我想知道文件的长度。我的意图是,当脚本逐行计算所有字符时,它会打印当前行和总行数,这样我就可以知道需要多少。

我执行了一个简单的 for 循环来计算行数,然后执行另一个 for 循环来计算字符并将它们放入字典中。但是,当我使用第一个 for 循环运行脚本时,它会提前停止。据我所知,它甚至没有进入第二个 for 循环。如果我删除这个循环,其余的代码就可以正常运行。这是什么原因造成的?

请原谅我的代码。它很简陋,但我为此感到自豪。

我的代码:

import string

fname = input ('Enter a file name: ')

try:
    fhand = open(fname)

except:
    print ('Cannot open file.')
    quit()

#Problematic bit. If this part is present, the script ends abruptly.
#filelength = 0
#for lines in fhand:
#    filelength = filelength + 1

counts = dict()
currentline = 1
for line in fhand:
    if len(line) == 0: continue
    line = line.translate(str.maketrans('','',string.punctuation))
    line = line.translate(str.maketrans('','',string.digits))
    line = line.translate(str.maketrans('','',string.whitespace))
    line = line.translate(str.maketrans('','',""" '"’‘“” """))
    line = line.lower()
    index = 0
    while index < len(line):
        if line[index] not in counts:
            counts[line[index]] = 1
        else:
            counts[line[index]] += 1
        index += 1
    print('Currently at line: ', currentline, 'of', filelength)
    currentline += 1

listtosort = list()
totalcount = 0

for (char, number) in list(counts.items()):
    listtosort.append((number,char))
    totalcount = totalcount + number

listtosort.sort(reverse=True)
for (number, char) in listtosort:
    frequency = number/totalcount*100
    print ('Character: %s, count: %d, Frequency: %g' % (char, number, frequency))

【问题讨论】:

  • 如果第一个循环存在,它将消耗文件中的所有行,而没有留下任何内容供第二个循环读取。您需要在循环之间执行fhand.seek(0) 来回退文件。
  • 当我试图计算我从古腾堡计划获得的《傲慢与偏见》时,我必须包括该行,因为它会在统计数据中计算这些引用。他们没有在其他翻译中被删除。这确实是一种临时解决方案。
  • 哦,我现在明白了。所以有一个隐藏的计数器可以跟踪我在哪一行,然后我必须用 fhand.seek(0) 重置它。我想我的想法是它会在每个 for 循环中自行重置。我不知道,谢谢。

标签: python-3.x loops


【解决方案1】:

您这样做的方式看起来不错,但是为了模拟您的问题,我下载并保存了一本 Guttenberg 教科书。这是一个unicode问题。解决它的两种方法。将其作为二进制文件打开或添加编码。由于是文本,我会选择 utf-8 选项。

我还建议你用不同的方式编码,下面是打开文件后关闭文件的基本结构

filename = "GutenbergBook.txt"
try:
    #fhand = open(filename, 'rb')
    #open read only and utf-8 encoding
    fhand = open(filename, 'r', encoding = 'utf-8')
except IOError:
    print("couldn't find the file")
else:
    try:
        for line in fhand:
            #put your code here
            print(line)
    except:
        print("Error reading the file")
finally:
    fhand.close()

【讨论】:

  • 谢谢。我会牢记这些特点。我仍然掌握打开命令、编码等的窍门。
猜你喜欢
  • 1970-01-01
  • 2021-08-10
  • 2021-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多