[英]How do I correctly turn words from a file into a tuple or list
該程序會打印,但它會完全按照它們的編寫方式打印我的文件中的內容
import random
def getWords(filename):
openFile = open(filename, 'r')
readFile = openFile.read()
listWords = []
listWords = [readFile]
tupleList = tuple(listWords)
return tupleList
nouns = "nouns.txt"
verbs = "verbs.txt"
prepo = "prepos.txt"
articles = "articles.txt"
prepositions = getWords(prepo)
nouns = getWords(nouns)
verbs = getWords(verbs)
articles = getWords(articles)
def sentence():
return nounPhrase() + " " + verbPhrase()
def nounPhrase():
return random.choice(articles) + " " + random.choice(nouns)
def verbPhrase():
return random.choice(verbs) + " " + nounPhrase() + " " + \
prepositionalPhrase()
def prepositionalPhrase():
return random.choice(prepositions) + " " + nounPhrase()
def main():
number = int(input("Enter the number of sentences: "))
for count in range(number):
print(sentence())
main()
我不完全確定如何將文件中的一組單詞轉換為元組或列表,以便以后用作隨機單詞選擇。
一個例子 output 是: a blake billy john 在 blake billy john 后面跑 a blake billy john 在 blake billy john 后面 一個 blake billy john 在 blake billy john 后面跑
而不是所需的 output 是:(只有一個正在輸入的單詞[隨機選擇]通過輸出)
布萊克跑在前面約翰跑在后面
(在這種情況下連貫性和語法不是問題)
您的 getWords function 需要的是在讀取文件后,用換行符將其拆分。 我假設您的文件格式類似於
noun1
noun2
noun3
etc
所以你的 function 應該是這樣的
def getWords(filename):
openFile = open(filename, 'r')
readFile = openFile.read().split('\n')
listWords = []
listWords = [readFile]
tupleList = tuple(listWords)
return tupleList
使代碼更干凈的建議:
def getWords(filename):
openFile = open(filename, 'r')
return openFile.read().split('\n') # split() automatically returns a list
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.