首页 > 解决方案 > 如何读取文本文件的每一行并将每一行转换为一个元组?

问题描述

我尝试逐行读取文本文件并将每一行转换为 tuple 。这是我的文本文件数据

danial feldroy - 两勺 django

james - 适合所有人的 python

我需要阅读每一行并将其转换为这样的元组("danial feldroy "," two scoops of django") ("james "," python for everyone")

我必须将此元组添加到列表中

nt = open('my_file.txt').readlines()
names_title = []
for book in nt:
    a = book.replace('-',',')
    convert_to_tuple = tuple(a)
    print(a)
    #but i have to remove the white spaces as well

结果 :

danial feldroy , two scoops of django

我期待这个

danial feldroy,two scoops of django
    

然后我想将每一行更改为一个元组

("danial feldroy","two scoops of django")

但是每当我使用tuple()它时,它都无法按预期工作?

和元组的输出

('d','a','n','i','a','l' etc ..

我期待这个("danial feldroy","two scoops of django")

标签: pythonlisttuples

解决方案


您是否尝试将循环内的内容更改为:

 nt = open('my_file.txt').readlines()
 names_title = []
 for book in nt:
     data_tuple = (x.strip() for x in book.split('-'))
     print(data_tuple)

问题是您试图将字符串转换为可迭代的元组,并将每个字符转换为字符串的特定字符。相反,使用split()你会将你想要的部分划分为某个字符


推荐阅读