我正在尝试解决python中的元组问题,我在终端上运行我的python代码,但每次运行它时,它都会将我存储的文件夹带回来,没有任何输出。这是代码:
name = raw_input("Enter file:")
if len(name) < 1 :
name = "mbox-short.txt"
handle = open(name)
count = dict()
fh = handle.read()
for line in fh :
lines = line.rstrip()
if lines.startswith('From '):
word = lines.split()``
words = word[5]
wordss = words.split()
wordsss = wordss[0]
for letters in wordsss :
count[letters] = wordsss.get(letter, 0) +1
lst = list ()
for k,v in count.items() :
lst.append( (k,v) )
lst.sort(k)
print lst
答案 0 :(得分:0)
name = raw_input("Enter file: ")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
hours = {}
# handle = open("mbox-short.txt")
for line in handle:
if line.startswith('From '):
hour = line.split()[-2].split(':')[0]
if hour in hours:
hours[hour] = hours[hour] + 1
else:
hours[hour] = 1
hours = sorted(hours.items())
for hour, count in hours:
print hour, count
<强>输出:强>
bharat@bhansa:~/Desktop/Stack$ python edit_narang.py Enter file: 04 3 06 1 07 1 09 2 10 3 11 6 14 1 15 2 16 4 17 2 18 1 19 1
答案 1 :(得分:0)
fh = handle.read()
for line in fh :
lines = line.rstrip()
在这些行中,您正在阅读所有文件内容,并将其作为fh
存储在string
中。现在当你在for line in fh
中迭代它时,你只是在line
中获得了单个字符,因此line.rstrip()
没有多大意义,if lines.startswith('From ')
也没有。