繁体   English   中英

Python,将文件中具有特定字符串的所有行添加到列表中,然后随机选择要打印的字符串?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM