[英]Print values from list based from separate text file
如何從單獨的文本文件中打印單詞列表? 我要打印所有單詞,除非單詞的長度為4個字符。
words.txt文件如下所示:
減少騙子散布收益說潛在的異常凝結溶解散亂
它總共有334個單詞。 我正在嘗試顯示列表,直到它到達長度為4的單詞並停止為止。
wordsFile = open("words.txt", 'r')
words = wordsFile.read()
wordsFile.close()
wordList = words.split()
#List outputs length of words in list
lengths= [len(i) for i in wordList]
for i in range(10):
if i >= len(lengths):
break
print(lengths[i], end = ' ')
# While loop displays names based on length of words in list
while words != 4:
if words in wordList:
print("\nSelected words are:", words)
break
5 9 11 7 6 8 9 11 9 4
選擇的單詞是:
減輕
強辯
傳播
否定
潛
異常
凝結
解散
貧嘴
要讀取文本文件中的所有單詞,並打印每個單詞,除非它們的長度為4:
with open("words.txt","r") as wordsFile:
words = wordsFile.read()
wordsList = words.split()
print ("Selected words are:")
for word in wordsList:
if len(word) != 4: # ..unless it has a length of 4
print (word)
稍后在您的問題中,您寫道:“我正在嘗試顯示前10個字” ...)。 如果是這樣,請添加一個計數器,如果其值小於等於10,則添加要打印的條件。
鑒於您只需要前10個字。 讀全部4行沒有多大意義。 您可以安全地閱讀第一篇,並節省一些時間。
#from itertools import chain
with open('words.txt') as f:
# could raise `StopIteration` if file is empty
words = next(f).strip().split()
# to read all lines
#words = []
#for line in f:
# words.extend(line.strip().split())
# more functional way
# words = list(chain.from_iterable(line.strip().split() for line in f))
print("Selected words are:")
for word in words[:10]:
if len(word) != 4:
print(word)
我留下了一些替代方法,但已將其注釋掉。
使用while循環進行編輯。
i = 0
while i < 10:
if len(words[i]) != 4:
print(words[i])
i += 1
由於您知道可以執行的迭代次數,因此可以使用for
循環隱藏迭代的機制。 一會兒不能很好地解決這個問題,當您不知道要執行多少次迭代時,最好使用它。
盡管我會使用for或while循環,就像Paul Rooney所建議的那樣,但是您也可以修改代碼。 創建列表長度[]時,將創建一個列表,其中包含wordList中包含的單詞的所有長度。
然后,使用for循環在lengths []中循環前10個長度。 如果需要使用此方法,則可以嵌套一個for循環,比較單詞和長度:
#lengths[] contains all the lengths of the words in wordList
lengths= [len(i) for i in wordList]
#foo[] cointains all the words in wordList
foo = [i for i in wordList]
#for the first 10 elements of lengths, if the elements isn't 4 char long
#print foo[] element with same index
for i in range(10):
if lengths[i] != 4:
print(foo[i])
if i >= len(lengths):
break
我希望這很清楚,這就是您想要的答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.