簡體   English   中英

關於將文件讀入 Python 中的列表的問題

[英]Question regarding to reading a file into a list in Python

單擊此處查看文件的屏幕截圖。 我正在編寫一個程序,它將 2 個文本文件讀入一個列表,然后要求用戶輸入一個名稱以檢查它是否是一個流行的名稱。 這是我到目前為止所做的:

girlFile = open('GirlNames.txt', 'r')
girlTexts = girlFile.readlines()
boyFile = open('BoyNames.txt', 'r')
boyTexts = boyFile.readlines()


choice = input("What gender do you want to enter: boy, girl, or both? ")

if choice == "boy":
    boyName = input("What is the boy's name? ")
    if boyName in boyTexts:
        print(boyName,"was a popular boy's name between 2000 and 2009.")
    else:
        print(boyName,"was not a popular boy's name between 2000 and 2009.")
elif choice == "girl":
    girlName = input("What is the girl's name? ")
    if girlName in girlTexts:
        print(girlName,"was a popular girl's name between 2000 and 2009.")
    else:
        print(girlName,"was not popular girl's name between 2000 and 2009.")
elif choice == "both":
    boyName = input("What is the boy's name? ")
    girlName = input("What is the girl's name? ")
    if boyName in boyTexts:
        print(boyName,"was a popular boy's name between 2000 and 2009.")
    else:
        print(boyName,"was not popular boy's name between 2000 and 2009.")
    if girlName in girlTexts:
        print(girlName,"was a popular girl's name between 2000 and 2009.")
    else:
        print(girlName,"was not a popular girl's name between 2000 and 2009.")
else:
    print("Invalid input, please restart the program.")

雖然該程序仍然有效,但除了“(那個名字)不是一個流行的名字......”之外我無法得到任何輸出,我認為我的問題是關於將文件讀入列表,或者可能是我找不到由於代碼,列表中的該名稱。 例如,如果我先輸入boy,它會問我你想找的男孩的名字,如果我輸入Jacob,他的名字在文本文件中,它會打印出(“Jacob 是一個受歡迎的男孩的名字2000 年到 2009 年之間。”),否則,打印出它不是。

因此,當返回文件中有新行時,在 readlines 變量中,將\n添加到該行的文本中。 這些可以用一個循環和rstrip function移除

boyFile = open('BoyNames.txt', 'r')
boyTexts = boyFile.readlines()
boyTexts = [name.rstrip('\n') for name in boyTexts]

您從未從列表項中刪除\n換行符。 你可以使用這樣的東西......

with open("BoyNames.txt", "r") as f:
    lines = f.readlines()
    name = input("What is the boy's name? ")
    for line in lines:
        if name == line.strip("\n"):
            print(f"{name} was a popular boy's name between 2000 and 2009.")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM