简体   繁体   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"))

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.

相关问题 在python中找到某个字符串后如何打印所有行? - How to print all the lines after it found certain string in python? 如何在 Python 中打印包含某个字符串的文本文件的行? - How to print the lines of a text file that contain a certain string in Python? 在 python 中,如何打印不包含某个字符串的行,而不是打印包含某个字符串的行: - In python, how can I print lines that do NOT contain a certain string, rather than print lines which DO contain a certain string: 如何只打印包含某个字符串的文件中的行? - How to only print lines from a file containing a certain string? 使用python从文本文件中删除不包含某些字符串的行 - Remove lines from a text file which do not contain a certain string with python 在python中导入txt文件,并在字符串中打印所有带有特定单词的行 - import a txt file in python and print all lines with specific word in string Python-输入文件中出现字符串的所有行和行号 - Python - All the lines and line numbers in which string occurs in the input file 从文件python中删除字符串和字符串之前的所有行 - remove string and all lines before string from file python 从随机生成的列表中选择-python - Choosing from a randomly generated list - python 如何从文本文件中随机打印多行(使用python) - How to print a number of lines randomly from a text file (using python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM