简体   繁体   English

将整数从文本文件中放入列表

[英]Putting integers into a list from a text file

I have a text file and I need to put the numbers in this file into a list like this: [[123,456],[234,567],[345,678]...] but I don't know how to do this as I ran into some error messages shown below.我有一个文本文件,我需要将这个文件中的数字放入这样的列表中: [[123,456],[234,567],[345,678]...]但我不知道如何在运行时执行此操作进入如下所示的一些错误消息。

My text file looks something like this (the --> are arrows in the original text file, but I don't know what they look like if I read the file using with open :我的文本文件看起来像这样( -->是原始文本文件中的箭头,但如果我使用with open读取文件,我不知道它们是什么样子:

# These are the ids for blablabla
# put the ids into a list like this [[123,456],[234,567],[345,678]...]
#id1 --> id2
#123 --> 456
#234 --> 567
#345 --> 678
#456 --> 789

What I tried to do initially was我最初尝试做的是

with open('mytxt.txt', 'r') as f:
    for line in range(3):
        next(f)
    for line in f:
        lst = list(map(int,line.split(',')))
        print(lst)[:10]

After running this, I got an error message <:-- language: lang-js --> invalid literal for int() with base 10: '123\t456\n' so I thought about stripping the '\n' and the 't' at the end of each line by running the following code:运行此程序后,我收到一条错误消息<:-- language: lang-js --> invalid literal for int() with base 10: '123\t456\n'所以我想剥离'\n'和通过运行以下代码在每行末尾't'

with open('ca-GrQc.txt', 'r') as f:
    for line in range(4):
        next(f)
    for line in f:
        lst = list(map(int,line.strip('\n').strip('t').split(',')))
        print(lst)[:10]

After running that I still got an error message invalid literal for int() with base 10: '123\t456' which I have no idea where the 't' comes from (and I am sure that 't' was not in the orginal file).运行之后,我仍然收到错误消息invalid literal for int() with base 10: '123\t456'我不知道't'来自哪里(我确信't'不在原始文件)。

Does anyone know why that happens and how to solve it, or is there a more efficient way of putting the numbers from the text file into a list?有谁知道为什么会发生这种情况以及如何解决它,或者有没有更有效的方法将文本文件中的数字放入列表中?

You can use regex to achieve your expected output.您可以使用正则表达式来实现您预期的 output。

import re
file1 = open("names_file.txt", "r")
l = file1.readlines()
new_list = []
for i in l:
    m = re.findall(r'\d+', i)
    new_list.append(m)
print(new_list)

Above code will give a list containing strings, if you want to convert it into integer type then add this code.上面的代码将给出一个包含字符串的列表,如果要将其转换为 integer 类型,请添加此代码。 This will give your expected output.这将给出您预期的 output。

for j in range(len(new_list)):
    for k in range(2):
        new_list[j][k] = int(new_list[j][k])
print(new_list)

There are two print statement in above code one will give list of list of string, and after conversion it will give list of list of integers.上面代码中有两个打印语句,一个会给出字符串列表,转换后会给出整数列表。 输出

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

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