我是学习如何使用 Python(或一般编码)的新手,我正在尝试制作一个 Twitter 机器人来发布我最喜欢的电视角色之一“Michael Scott”的名言。
我的所有报价都在 CSV 文件中。我现在要解决的问题是如何选择 CSV 中的特定行,获取存储在该行中的引述,并将其保存为变量。
我查看了有关选择特定行的其他文档,但它们似乎都试图做的不仅仅是选择一行。
这是我的代码。它返回存储在 CSV 中的所有引号。
import csv
with open('data.csv') as csvDataFile:
csvReader = csv.reader(csvDataFile)
for row in csvReader:
print(row[2])
--- 编辑以显示 CSV 的结构 ---
id_serial,id_season,quote,file_path,id_group,trigger_time
1,S1E01,"People say I am the best boss. They go ""god we've never worked at a place like this before. You're hilarious. And you get the best out of us.""",,001,09:00 AM EST
2,S1E01,I think this pretty much sums it up,/home/pi/Desktop/OfficialDundies/media/001.png,001,11:00 AM EST
如果我不够具体,我深表歉意。我仍然在这里学到很多东西。 :)
最佳答案
import csv
with open('data.csv') as csvDataFile:
data = list(csv.reader(csvDataFile))
print(data)
现在你已经得到列表 data
中的所有内容:
[['id_serial', 'id_season', 'quote', 'file_path', 'id_group', 'trigger_time'], ['1', 'S1E01', 'People say I am the best boss. They go "god we\'ve never worked at a place like this before. You\'re hilarious. And you get the best out of us."', '', '001', '09:00 AM EST'], ['2', 'S1E01', 'I think this pretty much sums it up', '/home/pi/Desktop/OfficialDundies/media/001.png', '001', '11:00 AM EST']]
第一个索引针对每一行,第二个索引针对该行的每一列。要获取报价,第二个索引必须是 2
。
您可以选择一个随机行(用于随机报价):
import random
i = random.randint(1, len(data) - 1)
randint(1, len(data) - 1)
将返回一个从索引 1 开始的随机整数,因为 CSV 文件的第一行包含列标题。
我们现在可以打印随机选择的报价:
print(data[i][2])
关于python - 如何使用 python 选择特定的 CSV 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55717807/