【问题标题】:Terminal returning directory without output everytime I run my code每次我运行我的代码时,终端都返回没有输出的目录
【发布时间】:2016-06-30 05:55:05
【问题描述】:

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

【问题讨论】:

  • 请更正代码中的缩进。
  • 您可以在终端中添加您正在使用的命令吗?
  • 查看下面的解决方案

标签: python ubuntu terminal


【解决方案1】:
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 输入文件: 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

【讨论】:

  • 我在这段代码中的索引中得到了数组。这里有什么问题 ? name = raw_input("Enter file:") if len(name)
  • 很抱歉,此代码无法理解,请以正确的身份将其发布在您的问题中。
【解决方案2】:
fh = handle.read()
for line in fh :
    lines = line.rstrip()

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

【讨论】:

    猜你喜欢
    • 2018-10-07
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 2020-02-23
    • 2021-10-23
    • 2022-01-03
    相关资源
    最近更新 更多