python - 将来自csv的字符串组合成一行
问题描述
我正在尝试从只有一列的 csv 文件中读取。例如,我需要将所有字符串组合成一个,Row[1]=="Hallo."
然后Row[2]=="Goodbye."
组合成string=="Hallo. Goodbye."
.
import csv
data=None
with open('reviews.csv',encoding='utf-8') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
data2=(row[0])
print(f'\n{data}.')
line_count += 1
data+=data2
print(f'Processed {line_count} lines.')
我得到的当前错误是:
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'
我已经搜索并阅读了一些帖子,但似乎无法理解。
解决方案
因为您要连接一堆字符串,所以请尝试使用带有简单生成器理解的字符串的 join 方法:
import csv
with open('reviews.csv',encoding='utf-8') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
data = "".join(row[0] for row in csv_reader if isinstance(row[0], str))
print(data)
print(f'Processed {csv_reader.line_num} lines')
请注意, csv_reader 在内部跟踪它已查看的行数。
推荐阅读
- java - CodingBat starOut,为什么使用子字符串不能正常工作
- kubernetes - 将本地文件复制到 aks 高级或标准存储
- python - 用 CSV 文件中的文本和整数值为汽车数据训练价格预测机器学习模型的最佳方法是什么?
- react-native - 使用 react-native-svg 时执行 UI 块时引发异常
- select - PySpark DataFrame 何时使用/不使用 Select
- ruby - gem 是否使用空格记录无法识别的选项?
- android - 如何在 Android Studio 中正确读取浮点特性
- javascript - getElementById 的问题
- angular - HMR 使用 Angular 9 + IVY 失败:类型 AppComponent 是 2 个模块声明的一部分:AppModule 和 AppModule
- c - 通过共享内存和管道的 IPC 给出分段错误:C 中的 11