Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

Python | Reading From A .txt file |

i am trying to make a program that selects a artist and prints a word from their song (all artists and song lines are in a .txt and should be chosen at random)

i am struggling to do this i have gotten this so far

def main():
    import time
    import os

    os.system('cls')
    print("███╗   ███╗██╗   ██╗███████╗██╗ ██████╗     ██████╗ ██╗   ██╗██╗███████╗")
    print("████╗ ████║██║   ██║██╔════╝██║██╔════╝    ██╔═══██╗██║   ██║██║╚══███╔╝")
    print("██╔████╔██║██║   ██║███████╗██║██║         ██║   ██║██║   ██║██║  ███╔╝") 
    print("██║╚██╔╝██║██║   ██║╚════██║██║██║         ██║▄▄ ██║██║   ██║██║ ███╔╝ ") 
    print("██║ ╚═╝ ██║╚██████╔╝███████║██║╚██████╗    ╚██████╔╝╚██████╔╝██║███████╗")
    print("╚═╝     ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═════╝     ╚══??═╝  ╚═════╝ ╚═╝╚══════╝")
    print("")
    print("")
    print("Made By *****")
    time.sleep(2)

content = []
with open('songs.txt', 'r') as f:
    for line in f:
        content.append(line.strip('
'))

    for i in content:
        if 'song 1' == i:
            print("")
        else:
            pass

any suggestions are appreciated


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a random function.

At the top of the code:

import random

Then run:

index = random.randint(0,len(content))

to index it later just use:

print(content[index])

So:

import random
def main():
    import time
    import os

    os.system('cls')
    print("███╗   ███╗██╗   ██╗███████╗██╗ ██████╗     ██████╗ ██╗   ██╗██╗███████╗")
    print("████╗ ████║██║   ██║██╔════╝██║██╔════╝    ██╔═══██╗██║   ██║██║╚══███╔╝")
    print("██╔████╔██║██║   ██║███████╗██║██║         ██║   ██║██║   ██║██║  ███╔╝") 
    print("██║╚██╔╝██║██║   ██║╚════██║██║██║         ██║▄▄ ██║██║   ██║██║ ███╔╝ ") 
    print("██║ ╚═╝ ██║╚██████╔╝███████║██║╚██████╗    ╚██████╔╝╚██████╔╝██║███████╗")
    print("╚═╝     ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═════╝     ╚══??═╝  ╚═════╝ ╚═╝╚══════╝")
    print("")
    print("")
    print("Made By *****")
    time.sleep(2)

content = []
with open('songs.txt', 'r') as f:
    for line in f:
        content.append(line.strip('
'))
index = random.randint(0, len(content)-1)
print(content[index])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...