[英]Reading a random line from a word doc and printing it
所以我有一個python的小項目。
到目前為止,我已經創建了一個文本文檔並放置了幾行歌曲名稱。
在我的代碼中,我使用了以下內容:
random_lines = random.choice(open("songs.txt").readlines())
這會隨機選擇代碼中的一行並且不做任何處理。
我問我從這里去哪里。 我需要在行上顯示每個單詞的第一個字母。 然后我需要一個計數器或某種類型來增加機會。 我還需要寫一些東西來檢查他們是否正確並添加到分數計數器中。
好的,現在繼續你的計划,很好。 現在您必須從行中的每個單詞中獲取第一個字母。 你可以這樣做:
res = []
for i in line.split():
res.append(i[0])
你在那里,你有列表 res 中每個單詞的第一個字母。 現在您需要檢查用戶是否正確輸入了標題。 也許最好的主意是將所有內容(在您的文件和用戶輸入中)保持為小寫,以便於檢查。 現在您只需要將用戶輸入轉換為小寫。 你可以這樣做:
user_entry = input('Song title:')
if user_entry.lower() == line.lower():
score += 3
else:
user_entry_2 = input('Song title:')
if user_entry_2.lower() == line.lower():
score += 1
else:
print('Game over.')
sys.exit()
你應該把它變成一個函數廣告,循環調用它,直到用戶錯過。 該函數可以返回您可以打印出的當前分數(在這種情況下,您應該刪除sys.exit()
調用)
我希望這已經足夠清楚了。 如果沒有,請在評論中寫下問題:)
假設您的隨機選擇字符串包含格式為{songname} - {artist}
然后您首先需要將歌曲名稱和藝術家作為單獨的字符串。
打印第一個字母並要求輸入。
之后,您需要比較字符串並對點進行一些邏輯處理。
points = 0;
while(1):
random_line = 'Song - artist' #change this with your random string
song, artist = random_line.split('-')
print("{0} - {1}".format(song.strip()[:2], artist.strip()[:2]))
for i in range(0,3):
if (i == 2):
print('You died with {} points'.format(points))
exit(0)
elif(random_line.lower() == input('Gues the song: ').lower()):
points += 2 - i
print('correct guess. points: ' + str(points))
break
else:
print('Try again')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.