簡體   English   中英

如何編寫一個程序來讀取包含單獨列中帶有數字的單詞的.txt文件並打印出具有最大數字的單詞?

[英]How to write a program that reads a .txt file that contains words with numbers in a separate column and print out the word with the biggest number?

我對編碼很陌生,所以這就是我現在所擁有的。 我在嘗試 select 最高數字並打印出與之對應的單詞時遇到問題。

編輯:我還應該編寫一個代碼,該代碼也忽略'#'字符及其后面的任何內容。

text = open('heroes.txt', 'r')
for line in sorted(text, key = lambda line: line.split()[1]):
    if not '#' in line:
        line.isalnum() or line == '_'
        continue

這是帶有列表的文本文件

這可能會奏效

text = open('heroes.txt', 'r')
data={}
for line in text.readlines():
    if line.startswith('#'):
        continue
    d_l=line.split()
    d_l=[[x.strip() for x in y] for y in d_l]
    data[d_l[0]]= d_l[1]

text.close() #remember to close file

for k,v in data.items():
    if v==max(data.values()):
        print(k)

根據 SuperStew 的回答,進行了更改以使其對初學者來說更直觀。 添加了評論。

text = open('heroes.txt', 'r')

# Empty dictionary
data = {}

# For every line in the file...
for line in text.readlines():
    # skip if line starts with #
    if line.startswith('#'):
        continue

    # Split the name into two parts, hero name and hero power.
    row = line.split()

    # Map row data to dictionary. Hero name will be key, hero power will be value.
    data[row[0]] = row[1]

# Remember to close the file
text.close()

# For every key value pair in data...
for k,v in data.items():
    # See if value is the max value. If so, print it.
    if v==max(data.values()):
        print(k)

有用的鏈接:

https://www.w3schools.com/python/ref_string_split.asp

https://www.w3schools.com/python/python_dictionaries.asp

暫無
暫無

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

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