简体   繁体   English

将文本文件转换为字符串或列表

[英]Converting the text file into a string or list

I have the following data in my text file:我的文本文件中有以下数据:

5*0 4 3 2 5 7 7 3 6 3 2 6 5*0 4 3 2 5 7 7 3 6 3 2 6

8*2 4 5 6 7 8 7 3 7 7 3 8*2 4 5 6 7 8 7 3 7 7 3

I want to work on the data in python.我想在 python 中处理数据。 so, I guessed it is better to convert it to string or list.所以,我猜最好将它转换为字符串或列表。

I used the following code:我使用了以下代码:

a = open('test.txt', 'r')
b = a.readlines()
c = [x.replace('\n','') for x in b]
print(c)

but it gives:但它给出了:

['5*0 4 3 2 5 7 7 3 6 3 2 6 ', ' 8*2 4 5 6 7 8 7 3 7 7 3']

I wondered to know how I can convert it to the following:我想知道如何将其转换为以下内容:

['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']

I would simply change the readlines by the read method (does not split the lines into different list items), then change the '\\n' newline character by spaces and finally split the string by spaces.我会简单地通过read方法更改readlines (不会将行拆分为不同的列表项),然后用空格更改'\\n'换行符,最后用空格拆分字符串。

a = open('test.txt', 'r')
b = a.read()
c = b.replace('\n', ' ').strip().split(' ')
a.close()
print(c)

I would suggest to use the with statement so as to not forget to close the file我建议使用with语句以免忘记关闭文件

with open('test.txt', 'r') as a:
    b = a.read()
c = b.replace('\n', ' ').strip().split(' ')
print(c)

try this尝试这个

a = open('test.txt', 'r')
b = a.readlines()

new_list = []
for line in b:
    for item in line.strip().split():
        new_list.append(item)
print(new_list)

I will convert this to list compression and edit the post, but here it is without我会将其转换为列表压缩并编辑帖子,但这里没有

a = open('test.txt', 'r')
b = a.readlines()
c = [a for n in str(b).split('\n') for a in n.split(' ') if a != '']
print(c)

>>> ['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']

you can do like this你可以这样做

c=['5*0 4 3 2 5 7 7 3 6 3 2 6 ', ' 8*2 4 5 6 7 8 7 3 7 7 3']
c=[j for i in c for j in i.split()]
print(c)

output输出

['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']
 with open('test.txt') as file: 
        print(file.read().split())

I used the with method to open and read the file along with the .read() method which reads the whole file instead of one line at a time, then the .split() method splits string at each ' ' , returning a list.我使用with方法打开和读取文件以及.read()方法,该方法读取整个文件而不是一次一行,然后.split()方法在每个' '处拆分字符串,返回一个列表。

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

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