[英]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"))
This is the part of the code for my random tips from a file so far.到目前为止,这是我从文件中随机提示的代码的一部分。 I wish to add another part of code where it adds all strings with any occurrence of the input placed after "/tip ", for example, if I were to type "/tip Hello", it would compile all lines in the text file with "Hello" in the string and do a random.choice() from the list, printing the one chosen.
我希望添加另一部分代码,它添加所有字符串,并在“/tip”之后添加任何出现的输入,例如,如果我输入“/tip Hello”,它将编译文本文件中的所有行字符串中的 "Hello" 并从列表中执行 random.choice() ,打印选择的那个。 I don't really know where to start with this, any help would be appreciated.
我真的不知道从哪里开始,任何帮助将不胜感激。 Thanks in advance!
提前致谢!
You don't have to store all of the lines in a list.您不必将所有行都存储在列表中。 You can read the lines, selecting one at random and discarding the rest.
您可以阅读这些行,随机选择一个并丢弃其余的。 This is called "resevoir sampling".
这称为“水库采样”。
Your code might look like this:您的代码可能如下所示:
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!"
As a more special case, this code randomly chooses a matching line from the tips file, but falls back to a random non-matching line if no match exists.作为更特殊的情况,此代码从提示文件中随机选择匹配行,但如果不存在匹配项,则回退到随机不匹配行。 It has the advantages of reading the input file exactly once, and not having to store the entire tips file in memory.
它的优点是只读取输入文件一次,而不必将整个提示文件存储在内存中。
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)
References:参考:
I think this is what you want, process each line of a text file, checking if the line has the word you're looking for.我认为这就是您想要的,处理文本文件的每一行,检查该行是否包含您要查找的单词。 If so, add it to a list, and the randomly select one "line" for all possible "lines".
如果是这样,将其添加到列表中,然后为所有可能的“行”随机选择一个“行”。
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.