[英]How do I allow Python to choose a random line from 2 text files (that are the same line) and then store them as variables?
因此,在過去的幾個小時中,我一直試圖解決無數次問題,這是:
我一直試圖讓程序在文本文件中選擇某一行,一旦完成,它就需要使用它選擇用於另一個文件的行號。
因此,假設該文件名為“ a.txt”,另一個文件名為“ b.txt”,我需要程序選擇一個隨機行(1,50),然后顯示它所選擇的行,但是它需要對另一個文件執行相同的操作,以便在兩個文件中選擇相同的行號。
我目前擁有的代碼:
import random
with open("a.txt") as word_file:
words = word_file.read().split()
randomw = random.choice(words)
with open("b.txt") as artist_file:
words = artist_file.read().split()
randname=random.choice(words)
print(randomw +" "+ randname)
謝謝你的幫助!
你很近。
import random
with open("a.txt") as word_file:
words = word_file.read().split()
random_line = random.choice(range(0, len(words))
randomw = words[random_line]
with open("b.txt") as artist_file:
words = artist_file.read().split()
randname=words[random_line]
print(randomw +" "+ randname)
基本上,您需要random.randint
:
import random
with open('a.txt') as f1, open('b.txt') as f2:
data1 = f1.readlines()
index = random.randint(0, len(data1))
line1 = data1[index]
try:
line2 = f2.readlines()[index]
except IndexError:
line2 = None
print("Not enough lines, dude!")
首先選擇一個隨機數,並在閱讀行時參考。
此外,如果這是一個現實世界中的問題,您將不總是知道行數,則可能需要獲取每個文件的行數,對這兩個數字進行排序,然后將隨機行強制在較短的范圍內(按行計數)文件。
在迭代時使用enumerate
獲取行和行號:
import random
with open("a.txt") as word_file:
number, line1 = random.choice([(number, line) for number, line in enumerate(word_file)])
with open("b.txt") as artist_file:
line2 = artist_file.readlines()[number]
將兩個文件壓縮在一起,然后選擇一個元組
with open("a.txt") as word_file, open("b.txt") as artist_file:
randomw, randname = random.choice(list(zip(word_file, artist_file)))
這很簡潔,但要付出代價: random.choice
需要將全部內容讀入內存。
如果知道多少行,您可以簡單地隨機選擇一個行號。
# n == number of lines
random_line = random.randint(0, n-1)
with open("a.txt") as word_file, open("b.txt") as artist_file:
for i, pair in enumerate(zip(word_file, artist_file)):
if i == random_line:
break
randomw, randname = pair
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.