簡體   English   中英

嘗試將用戶輸入的整數與文本文件進行比較,並從該txt文件輸出某些行

[英]Trying to Compare an Integer input by user to a text file and outputting Certain lines from that txt file

我正在嘗試創建一個接受數字並將其與txt文件中的相同數字進行比較的函數。 如果有數字,則輸出整行,否則輸出無數字。 目前只有9行。

我的txt文件(稱為nbaPointsLeaders.txt)如下

    1. James Harden, Houston Rockets, 30.4
    2. Anthony Davis ,New Orleans Pelicans, 28.1
    3. LeBron James, Cleveland Cavaliers, 27.5
    4. Damian Lillard, Portland Trail Blazers, 26.9
    5. Giannis Antetokounmpo, Milwaukee Bucks, 26.8
    6. Kevin Durant, Golden State Warriors, 26.4
    7. Russell Westbrook, Oklahoma City Thunder, 25.4
    8. Kyrie Irving, Boston Celtics, 24.4
    9. LaMarcus Aldridge, San Antonio Spurs, 23.1

如果用戶輸入1,則輸入整個第一行。

我遇到的另一個問題是:

    TypeError: 'in <string>' requires string as left operand, not int

每當我要求用戶輸入數字時,就會出現此問題。

這是我到目前為止提出的代碼。 我是python的初學者,所以它也可能很明顯。

    def leaderInPoints(number):
        number = int(input("What number from 1-9 would you like to see?"))
        with open('nbaPointsLeader.txt','r') as file:
              return [i for i in f if number in i])

任何幫助是極大的贊賞!

def leaderInPoints(number):

    number = int(input("What number from 1-9 would you like to see?"))
    file = open('nbaPointsLeader.txt','r')
    # get all lines
    content = file.readlines()
    # we get the nth line
    return content[number]

暫無
暫無

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

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