每次运行cod时返回没有输出的目录的终端

2024-09-29 22:31:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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 

Tags: 代码nameinforifcountlineword
2条回答
fh = handle.read()
for line in fh :
    lines = line.rstrip()

在这些行中,您读取所有文件内容并将其存储在fh中作为string。现在,当您在for line in fh中对它进行迭代时,您只得到line中的单个字符,因此line.rstrip()没有太大意义,if lines.startswith('From ')

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

相关问题 更多 >

    热门问题