简体   繁体   English

迭代文本文件中的数字

[英]Iterating over numbers in a text file

I have a .txt file with 1,000 numbers that are only separated by a ',' .我有一个包含 1,000 个数字的 .txt 文件,这些数字仅由','分隔。 When I open the file into python it reads it as one large string and therefore is only one line.当我将文件打开到 python 时,它会将它读取为一个大字符串,因此只有一行。 I need to figure out a way to convert each number between the commas into an int so I can iterate over them.我需要想办法将逗号之间的每个数字转换为int以便我可以迭代它们。 This is the code I have so far:这是我到目前为止的代码:

with open('HW5.txt') as f:
    data = f.read()
    print(type(data))
    newdata = data.replace(',',' ')
    data_seperate = newdata.replace(' ', '\n')
    print(data_seperate)
    print(len(data_seperate))
f.close()

It prints out each number on a new line, but the numbers are still strings and python counts each individual number as a character, not making each number a single integer.它在新行上打印出每个数字,但这些数字仍然是字符串,python 将每个单独的数字视为一个字符,而不是将每个数字设为单个整数。 How do I deal with this?我该如何处理? I am new to working with .txt files so the properties are confusing me.我刚开始使用 .txt 文件,因此属性让我感到困惑。 Trying to convert print(int(data_seperate)) returns this error:尝试转换print(int(data_seperate))返回此错误:

ValueError: invalid literal for int() with base 10: '798\n441\n687\n780\n103\n405\n363\n66\n481\n171\n549\n449\n135\n229\n689\n248\n374\n697\n502\n209\n699\n684\n377\n235\n819\n471\n189\n43\n696\n999\n769\n501\n148\n474\n733\n729\n427\n710\n911\n207\n2

With map :map

with open("HW5.txt") as f:
    data = [*map(int, f.read().split(","))]

>>> data
[798, 441, 687, 780, 103, 405, 363, 66, 481, 171, 549, 449, 135, 229,
 689, 248, 374, 697, 502, 209, 699, 684, 377, 235, 819, 471, 189, 43,
 696, 999, 769, 501, 148, 474, 733, 729, 427, 710, 911, 207, 25, 785,
 855, 550, 481, 735, 832, 791, 970, 225, 559, 182, 922, 717, 723, 113,
 260, 166, 294, 97, 3, 323, 835, 18, 653, 876, 264]

Here's one approach using str.split and map .这是使用str.splitmap的一种方法。 Note that I'm using rstrip() here in case there's a trailing newline in the file, as we do have here.请注意,我在这里使用rstrip()以防文件中有一个尾随换行符,正如我们在这里所做的那样。

sample_file_contents = """\
1,2,3,4,5,6,7,8,9
"""

num_list = sample_file_contents.rstrip().split(',')
numbers = list(map(int, num_list))

print(numbers)

Output:输出:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM