每次运行我的代码时,终端返回目录没有输出

时间:2016-06-30 05:55:05

标签: python ubuntu terminal

我正在尝试解决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 

2 个答案:

答案 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

请仔细阅读:http://www.pythonlearn.com/html-007/cfbook011.html

答案 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 ')也没有。