python - 如何读取文本文件的每一行并将每一行转换为一个元组?
问题描述
我尝试逐行读取文本文件并将每一行转换为 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")
!
解决方案
您是否尝试将循环内的内容更改为:
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()
你会将你想要的部分划分为某个字符
推荐阅读
- javascript - 如何使用javascript读取xml中的逗号分隔值
- php - 如何在 php shell_exec 中使用“dns-sd”命令?
- php - 如何解决 php 7.1.3 和 jpgraph 4.2.6 中的“Uncaught TypeError: Argument 1 passed to JpGraphException::defaultHandler()”问题?
- python - 将读取的文件与同名的不同格式文件一起移动
- java - 如何在 Kotlin Spring 项目中使用 Java 主类?
- c - 如何使用 fgets 函数来保存文本文件中的特定单词和推荐的数据类型以进行保存?
- api - 如何在 JMeter 中发送带有可变路径参数的 GET 请求?
- dynamics-crm - 使用 fetchxml 创建“ALL”选项
- c++ - C++ 表达式模板模棱两可的运算符重载
- r - 过滤最大日期的数据并提取最近 3 个月的数据