【问题标题】:Append next word into a list from a text file in python and print it columnwise将下一个单词从python中的文本文件附加到列表中并按列打印
【发布时间】:2018-12-06 08:29:50
【问题描述】:
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

我知道我的代码不正确。特别是在 append 语句和 increment 语句期间。我的问题是: 一种。正确的说法是什么? 湾。我会怎么做才能得到一个 coumnwise 输出,特别是如果有大量的单词,换句话说,我可以换成一列吗?

预期输出

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

这里绝对是初学者。

【问题讨论】:

  • 我给出的文本文件示例是 foo.txt 。很抱歉在那里不清楚。将编辑它。
  • 感谢您的建议。会的。

标签: python printing append output


【解决方案1】:

这很有效,我主要使用您的代码,以便您轻松理解如何改进:

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) )

【讨论】:

  • 非常感谢!不过,在将文本沿列包装的一些帮助将是一个真正的帮助。
【解决方案2】:

一个。字符串方法 '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)))

【讨论】:

  • 非常有帮助!谢谢! :)
猜你喜欢
  • 2016-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-01
相关资源
最近更新 更多