试图用Python计算文本文件中的字母频率

时间:2015-04-09 18:27:28

标签: python string object readlines

我有一个程序可以计算特定文本文件中的字母,(在我的例子中," Words.txt")。但是,当我尝试更改代码以接受用户输入而不是查找特定文件时,我得到以下内容: - ' STR'对象没有属性' readlines'

我确信这是我正在做的事情,但我不明白为什么。我的代码如下:

import string
#fname=raw_input("Enter file name: ")
fname=open('words.txt', 'r')

#if len(fname) < 1 : fname = "words.txt"
file_list = fname.readlines()

freqs = dict()
for line in file_list:
line = filter(lambda x: x in string.letters, line.lower())
for char in line:
    if char in freqs:
        freqs[char] += 1
    else:
        freqs[char] = 1
lst = list()
for key, val in freqs.items():
  lst.append( (val, key) )

lst.sort(reverse=True)

for key, val in lst[:] :
    print key, val

4 个答案:

答案 0 :(得分:1)

raw_input获得的只是一个包含文件名称的字符串。你仍然需要open才能获得实际的文件句柄。

filename = raw_input("Enter file name: ")
fname = open(filename, 'r')

此外,您可能希望使用with,以便在执行结束时自动关闭文件。而不是将所有行读入列表,您可以直接迭代文件。

filename = raw_input("Enter file name: ")
with open(filename, 'r') as fname:
    freqs = dict()
    for line in fname:
        ...

最后,您可以查看collections.Counter ...

答案 1 :(得分:0)

尝试:

fname = raw_input("Enter file name: ")
fname = open(fname, 'r')

另外两条建议:

1)处理文件时使用with语句(https://docs.python.org/2/tutorial/inputoutput.html

2)无需在file_list中存储所有行,只需遍历文件对象

filename = raw_input("Enter file name: ")
with open(filename, 'r') as fil:
    for line in fil:
        ...

答案 2 :(得分:0)

问题是readlines()只能在文件输入上调用。用户输入(字符串)的等效值为splitlines()

答案 3 :(得分:0)

假设您希望用户提供文件名(如我提供更多详细信息时提供的其他答案中所述),您只需执行以下操作:

fname=raw_input("Enter file name")
file_list = open(fname).readlines()

如果您希望用户输入数据,您可以这样做 file_list = sys.stdin.readlines()

另请注意,处理文件的首选方法是使用“with”

with open("x.txt") as f:
    for line in f: 
       #process each line

这会在你完成时处理关闭文件,并且还允许你将f视为迭代器(这样你就可以根据需要读取每一行而不是一次读取所有行)

最后,如果您确实想要从stdin或文件中读取,至少在Unix-y操作系统下,可以使用上面的sys.stdin.readlines位,如果要从文件中读取,请执行{{1 }}

相关问题