[英]Append next word into a list from a text file in python and print it columnwise
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
我知道我的代碼不正確。 特別是在追加語句和增量語句期間。 我的問題是: 什么是正確的陳述? 灣 我要怎么做才能得到類似的輸出,尤其是當有很多單詞時,換句話說,我可以包裝在列中嗎?
預期產量
number instances name instances null instances
4 1 Mathew 1 has, dogs, 5
and, a, cat
這里絕對是初學者。
一種。 字符串方法'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"):
灣 如果要打印列輸出,則可以使用字符串方法“ format”:
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)))
這行得通,我主要使用了您的代碼,因此您很容易理解如何改進:
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) )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.