【问题标题】:Converting the text file into a string or list将文本文件转换为字符串或列表
【发布时间】:2020-11-17 18:10:48
【问题描述】:

我的文本文件中有以下数据:

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

我想在 python 中处理数据。所以,我猜最好将其转换为字符串或列表。

我使用了以下代码:

a = open('test.txt', 'r')
b = a.readlines()
c = [x.replace('\n','') for x in b]
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']

我想知道如何将其转换为以下内容:

['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']

【问题讨论】:

  • 为什么不只是a.read().split()

标签: python python-3.x string list text-files


【解决方案1】:

我只需通过read 方法更改readlines(不会将行拆分为不同的列表项),然后将'\n' 换行符更改为空格,最后将字符串拆分为空格。

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

我建议使用with 语句,以免忘记关闭文件

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

【讨论】:

  • 感谢您的回复。我测试了这个,问题是它在删除'\n'时会生成空元素'' ['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']
【解决方案2】:

试试这个

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)

【讨论】:

    【解决方案3】:

    你可以这样做

    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)
    

    输出

    ['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']
    

    【讨论】:

    • 感谢您的回复,是的,效果很好。谢谢
    【解决方案4】:

    我会将其转换为列表压缩并编辑帖子,但这里没有

    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']
    
    

    【讨论】:

    • 感谢您的回复,这个给了我这个错误:'list' object has no attribute 'split'
    • 现在试试,需要转成字符串
    【解决方案5】:
     with open('test.txt') as file: 
            print(file.read().split())
    

    我使用with 方法打开和读取文件以及.read() 方法读取整个文件而不是一次读取一行,然后.split() 方法在每个' ' 处拆分字符串,返回一个列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 2019-01-08
      相关资源
      最近更新 更多