【问题标题】:How to convert strings in a text file into integers and store them in another file?如何将文本文件中的字符串转换为整数并将它们存储在另一个文件中?
【发布时间】:2016-03-14 04:02:01
【问题描述】:

如何读取包含以下项目列表的文本文件:

    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 值,为文件中的每个单词获取一个唯一值.到目前为止我做错了什么?

【问题讨论】:

  • Stack Overflow 不是代码编写或教程服务。请edit您的问题并发布您迄今为止尝试过的内容,包括示例输入、预期输出以及任何错误或回溯的全文
  • 对此我很抱歉。我改了。
  • 听起来你想写一个hash function。请注意,Python 提供了一个很好的方法:hash()
  • 除此之外,对于任何 xyyyyyy,您的方法都会产生相同的数字,其中 x 是第一个字母,yyyyyy 是其余字母的排列。

标签: python file file-io


【解决方案1】:

代码:

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

它在做什么:

  1. 首先打开文件list.txt
  2. 使用 Python 的列表解析语法找出每个字符的 ord(character)。
  3. 获取列表中所有值的总和并打印出来

注意

列表推导等价于:

numbers = []
for word in lines:
    for character in word:
        numbers.append(ord(character))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-15
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多