将下一个单词添加到python中文本文件的列表中,并按列打印

时间:2018-12-06 08:29:50

标签: python printing append output

number=[]
name=[]
null=[]
fh = open("foo.txt","r")
for line in fh:
 words=line.split()
 for word in words:
    if(word=="number"):
        number.append(word+1)
        print(word)
        word=word+2
    if(word=="name"):
        name.append(word+1)
        word=word+2
    else:
        null.append(word+1)
        word=word+2
print("number " " instances " " name " " instances " " null " " instances ")
print(number, len(number), name, len(name), null, len(null) )
fh.close()

这是我最小的python代码。我的目的是按列打印功能(例如名称)及其实例数。我的测试文件(foo.txt)具有以下顺序

name Mathew
null has
number 4
null dogs
null and
null a 
null cat

我知道我的代码不正确。特别是在追加语句和增量语句期间。我的问题是: 一种。什么是正确的陈述? b。我该怎么做才能获得同等输出,特别是如果有很多单词的话,换句话说,我可以包装在列中吗?

预期产量

number instances      name     instances     null         instances
  4        1         Mathew        1       has, dogs,         5
                                           and, a, cat

这里绝对是初学者。

2 个答案:

答案 0 :(得分:0)

a。字符串方法'split'-返回值列表,因此'words'变量将是文件当前行中的单词列表。 当您迭代“单词”时-迭代当前行中的每个单词,因此您不需要它。

 for line in fh:
    words=line.split()
    if (words[0] == "number"):
        number.append(int(words[1]))
        print(words[1])
    if (words[0] == "name"):
        name.append(words[1])
    else:
        null.append(words[1])

如果名称可以包含多个单词,则可以使用:

name.append(" ".join(words[1:]))

如果您不需要从文件中分离“空”值和“数字”,则可以使用:

elif (words[0] == "name"):

b。如果要打印按列输出,则可以使用字符串方法“格式”:

print("numbers: {:>20}, instances: {:>20}".format(str(number), len(number)))
print("name:    {:>20}, instances: {:>20}".format(str(name), len(name)))
print("null:    {:>20}, instances: {:>20}".format(str(null), len(null)))

答案 1 :(得分:0)

这可行,我主要使用了您的代码,以便您轻松理解如何进行改进:

name=[]
null=[]
number=[]
fh = open("foo.txt","r")
for line in fh:
    word= line.split()[0]
    if word == "name":
        name.append(line.rstrip('\n').split()[1])
    elif word =="number":
        number.append(line.rstrip('\n').split("number")[1])
    else:
        null.append(line.rstrip('\n').split("null")[1])

print("number " " instances " " name " " instances " " null " " instances ")
print(" ".join(str(x) for x in number), len(number), " ".join(str(x) for x in name), len(name), " ".join(str(x) for x in null), len(null) )
相关问题