如何阅读包含以下项目列表的文本文件:
milk
eggs
bacon
并通过将它们的ord()值相加并将它们存储在另一个文件中或通过覆盖它们的值将它们存储在同一个文件中来将它们转换为整数?
到目前为止,我有:
with open("grocery_items.txt") as f:
items = [word.strip() for word in f]
text_file = open("item_ordvals.txt", "w+")
c = 2
for i in items:
for k in i:
result = ord(i[0])
result = result * c + ord(i[k])
text_file.close()
我从名为" grocery_items.txt"的文件中读取每个项目。并将其存储在名为items的列表中。 我试图做的主要是通过将项目列表中单词的第一个字母乘以常数c,然后将其添加到单词中其余字母的ord值,为文件中的每个单词获取一个唯一值。到目前为止我做错了什么?
答案 0 :(得分:0)
代码:
with open('list.txt', 'r') as f:
lines = [line for line in f.read().split('\n')]
numbers = [[ord(character) for character in word] for word in lines] # Use list comprehension to find ord() of each character.
print([word for word in lines][0], sum(numbers[0]))
print([word for word in lines][1], sum(numbers[1]))
print([word for word in lines][2], sum(numbers[2]))
LIST.TXT:
milk
eggs
bacon
输出:
milk 429
eggs 422
bacon 515
它在做什么:
list.txt
注意
列表理解等同于:
numbers = []
for word in lines:
for character in word:
numbers.append(ord(character))