Python 如何编写一个程序来读取一个.txt文件,该文件在一个单独的列中包含数字单词,并打印出数字最大的单词?
我对编码非常陌生,所以这就是我现在所拥有的一切。我在尝试选择最高的数字并打印出与之对应的单词时遇到了问题 编辑:我还应该编写一个代码,同时忽略Python 如何编写一个程序来读取一个.txt文件,该文件在一个单独的列中包含数字单词,并打印出数字最大的单词?,python,sorting,Python,Sorting,我对编码非常陌生,所以这就是我现在所拥有的一切。我在尝试选择最高的数字并打印出与之对应的单词时遇到了问题 编辑:我还应该编写一个代码,同时忽略“#”字符及其后面的任何内容 text = open('heroes.txt', 'r') for line in sorted(text, key = lambda line: line.split()[1]): if not '#' in line: line.isalnum() or line == '_' c
“#”
字符及其后面的任何内容
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)
这可能会奏效
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)
根据Supersew的答案,对其进行了修改,使其对初学者来说更直观。补充评论
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)
有用链接:
基于Supersew的答案,对其进行了修改,使其对初学者来说更加直观。补充评论
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)
有用链接:
如果适用,请选择原始文本而不是屏幕截图:数据样本、代码、控制台输出、错误文本等。您对编码和尝试使用lambda非常陌生吗?我建议不要,这不是直觉。我的朋友试图帮助我。我不太清楚这是什么意思。如果有疑问,请查阅文档。这里是它所说的。在适用的情况下,喜欢原始文本而不是屏幕截图:数据样本、代码、控制台输出、错误文本等。您对编码和尝试使用lambda非常陌生吗?我建议不要,这不是直觉。我的朋友试图帮助我。我不太清楚这是什么意思。如果有疑问,请查阅文档。这是它说的。非常感谢你!!非常感谢你!!这对我来说更容易理解。非常感谢。这对我来说更容易理解。非常感谢。