[英]Python, Adding all lines with a certain string from a file to list then randomly choosing which string to print?
import random
com=input("")
if com.startswith("/tip"):
numlines=sum(1 for line in open("C:\\Users\\Jace\\Desktop\\Python Programs\\Quote\\tip.txt"))-1
randomint=random.randint(0, numlines)
with open("C:\\Users\\Jace\\Desktop\\Python Programs\\Quote\\tip.txt", "r") as f:
i=1
for line in f:
if i==randomint:
break
i+=1
print(line.strip("\n"))
到目前為止,這是我從文件中隨機提示的代碼的一部分。 我希望添加另一部分代碼,它添加所有字符串,並在“/tip”之后添加任何出現的輸入,例如,如果我輸入“/tip Hello”,它將編譯文本文件中的所有行字符串中的 "Hello" 並從列表中執行 random.choice() ,打印選擇的那個。 我真的不知道從哪里開始,任何幫助將不勝感激。 提前致謝!
您不必將所有行都存儲在列表中。 您可以閱讀這些行,隨機選擇一個並丟棄其余的。 這稱為“水庫采樣”。
您的代碼可能如下所示:
import random
def random_line(iterator):
result = None
for n, item in enumerate(iterator):
if random.randint(0,n) == 0:
result = item
return result
# A random line
with open('tip.txt') as f:
print random_line(f) or "No tip for you!"
# A random line that has 'Hello'
with open('tip.txt') as f:
print random_line(line for line in f if 'Hello' in line) or "nothin!"
作為更特殊的情況,此代碼從提示文件中隨機選擇匹配行,但如果不存在匹配項,則回退到隨機不匹配行。 它的優點是只讀取輸入文件一次,而不必將整個提示文件存儲在內存中。
import random
def random_line_with_fallback(iterator, match = lambda x: True):
result_match = None
result_all = None
n_match = n_all = 0
for item in iterator:
if match(item):
if random.randint(0, n_match) == 0:
result_match = item
n_match += 1
if random.randint(0, n_all) == 0:
result_all = item
n_all += 1
return (result_match or result_all).strip()
# A random line
with open('tip.txt') as f:
print random_line_with_fallback(f)
# Another way to do a random line. This depends upon
# the Python feature that "'' in line" will always be True.
com = ''
with open('tip.txt') as f:
print random_line_with_fallback(f, lambda line: com in line)
# A random line that has 'Hello', if possible
com = 'Hello'
with open('tip.txt') as f:
print random_line_with_fallback(f, lambda line: com in line)
參考:
我認為這就是您想要的,處理文本文件的每一行,檢查該行是否包含您要查找的單詞。 如果是這樣,將其添加到列表中,然后為所有可能的“行”隨機選擇一個“行”。
lines = []
with open("tip.txt", "r") as f:
for line in f:
if com in line:
lines.append(line)
print(random.choice(lines))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.