[英]I get this error: ValueError: invalid literal for int() with base 10: '\n'
[英]I get “ValueError: invalid literal for int() with base 10: ''” when splitting text
這是我的任務:
我目前在第 2a 部分(打印所有上場時間超過 1700 分鍾的球員)。
到目前為止,這是我的代碼:
def part1():
createfile=open("Assignment4.txt", "a+")
createfile.write(f"Player Name MinsPlayed Goals Assists YellowCard\n")
createfile.write(f"Lionel Messi 1943 19 4 4\n")
createfile.write(f"Robert Lewandowski 1864 28 6 2\n")
createfile.write(f"Harry Kane 2017 14 11 1\n")
createfile.write(f"Jack Grealish 1977 6 10 6\n")
createfile.write(f"Cristiano Ronaldo 1722 19 3 1\n")
createfile.write(f"Zlatan Ibrahimovic 1102 14 1 2\n")
createfile.write(f"Gerard Moreno 1735 14 2 3\n")
createfile.write(f"Romelu Lukaku 1774 18 6 4\n")
createfile.write(f"Kylian Mbappe 1706 18 6 3\n")
createfile.write(f"Erlin Haaland 1542 17 4 2")
createfile.close()
part1()
def part2():
filetoopen=open("Assignment4.txt", "r")
for line in filetoopen.readlines():
linetosplit=line.split(' ')
players = []
player_name = (linetosplit[0] + ' ' + linetosplit[1])
mins_played = (linetosplit[2])
goals = (linetosplit[3])
assists = (linetosplit[4])
yellow_card = (linetosplit[5])
players.append([player_name, mins_played, goals, assists, yellow_card])
filetoopen.close()
if mins_played > 1700:
print(player_name)
part2()
當我運行它時,會彈出此錯誤消息
類型錯誤:“str”和“int”的實例之間不支持“>”
然后我嘗試通過更改來修復它
mins_played = (linetosplit[2])
至
mins_played = int(linetosplit[2])
但隨后彈出此錯誤消息
ValueError: int() 以 10 為底的無效文字:''
檢查linetosplit
實際返回的內容。 在這種情況下,您會看到它返回
['Player', 'Name', '', '', '', '', '', '', '', '', '', 'MinsPlayed', '', 'Goals', '', '', 'Assists', 'YellowCard\n']
['Lionel', 'Messi', '', '', '', '', '1943', '', '', '', '', '', '', '', '19', '', '', '', '', '', '4', '', '', '', '', '', '', '4\n']
['Robert', 'Lewandowski', '', '', '1864', '', '', '', '', '', '', '', '28', '', '', '', '', '', '6', '', '', '', '', '', '', '2\n']
...
因為所有的空間都被分割了。 正如@Reti43 所述, line.split(' ')
和line.split()
之間存在差異。
但是,在您的情況下,這並不能完全解決您的問題。 由於文件的第一行是每列的定義。 而且您不能將此字符串轉換為 integer。
解決此問題的一種方法是在循環時不包括第一行。 有多種不同的方法可以做到這一點,但我通過排除列表的第一項來使用列表操作。
for line in filetoopen.readlines()[1:]:
# Code
這不包括第一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.