[英]import a txt file in python and print all lines with specific word in string
[英]How do I import a specific word from a .txt file into Python as a string variable?
我正在嘗試將 .txt 文件用作大約 4000 個不同單詞的本地數據庫。 它們按以下格式組織:
wordOne
wordTwo
wordThree
wordFour
...
wordFourThousand
每個單詞都有自己單獨的一行。 我的目標是能夠基於隨機變量從此文本文件中導入特定單詞。 我在下面舉了一個例子。 忽略我糟糕的駝峰式習慣。
import random
wordName=random.randint(1,4000)
with open('wordList.txt') as wordList:
#use the variable wordName to open the word on that particular line number in the .txt file and set it as a variable named wordString
print(wordString)
因此,如果變量 wordName 等於 32,它將打開文本文件第 32 行的單詞並將其打印到控制台。 我希望這不是一個簡單的問題,我對 Python 有點陌生,並試圖練習將數據從一個源移動到另一個源。 我真的很感謝你的幫助!
你可以做:
words = wordlist.readlines()
然后可以這樣做:
words[wordName - 1]
要檢索您想要的單詞,如果將單詞保存為全局變量,您也不必重新打開文本文件。
將 4k 字讀入內存是小菜一碟,所以我不會在這里優化任何東西。 最簡單的方法是使用random.choice()
:
import random
with open('filename.txt') as fp:
words = list(fp)
random_word = random.choice(words).strip() # strip will remove the trailing \n
執行您所描述的操作的最簡單方法是使用讀取行方法。
假設以下是您的文本文件
文字.txt:
one
two
three
...
您將執行以下操作:
with open("words.txt") as textFile:
words = textFile.readlines()
print(words[1])
輸出
two
記住列表索引從零開始,所以如果你想要words[i]
where i = 1
返回第一個元素,你會做words[i + 1]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.