用Python编写CSV文件
我编写了一个python脚本来访问一个站点,并在该站点上为我做了一次特定的搜索,以扫描搜索结果 我将结果的返回写为用Python编写CSV文件,python,pandas,csv,Python,Pandas,Csv,我编写了一个python脚本来访问一个站点,并在该站点上为我做了一次特定的搜索,以扫描搜索结果 我将结果的返回写为txt clear = self.browser.find_elements_by_class_name('Whitebackground') for scrape in clear: with open('result.txt', 'a') as writer: writer.write(scrape.text) writer.write
txt
clear = self.browser.find_elements_by_class_name('Whitebackground')
for scrape in clear:
with open('result.txt', 'a') as writer:
writer.write(scrape.text)
writer.write('\n')
writer.close()
我想返回CSV格式的结果,以便在Excel中打开
clear = self.browser.find_elements_by_class_name('Whitebackground')
for scrape in clear:
with open('result.csv', 'a') as writer:
writer.write(scrape.text)
writer.write('\n')
writer.close()
我的问题是我必须填写4列
我就是这样得到我现在的结果的
656473930362736
The car needs to change the oil
Model: sedan
type of fuel: Gasoline
我希望以这种方式接收CSV中的结果
'Number'; 'description'; 'Model'; 'Type of fuel'
6564...; The car needs..; sedan ; Gasoline
“编号”
,“说明”
,“型号”
,“燃料类型”
将按列列出标题
“6564…”
,“汽车需要…”
,“轿车”
,“汽油”
将是列中的行
有人知道我该怎么做吗???如果你能将数据转换成字典,那就太简单了:
data = []
datapoint = {}
datapoint['Number'] = 656473930362736
datapoint['Description'] = "The car needs to change the oil."
datapoint['Model'] = "Sedan"
datapoint['Type of Fuel'] = "Gasoline"
data.append(datapoint)
fieldnames = ['Number','Description','Model','Type of Fuel']
def filewriter(filename, data, fieldnames):
with open (filename, "w", newline='', encoding='utf-8-sig') as csvfile:
csvfile = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=',', dialect='excel')
csvfile.writeheader()
for row in data:
csvfile.writerow(row)
filewriter("out.csv", data, fieldnames)
将数据转换为字典是一个单独的问题,但如果数据结构良好,则应该没有什么大不了的。只需通过拆分为元素来解析文本:
txt = "656473930362736\n" \
"The car needs to change the oil\n" \
"Model: sedan\n" \
"type of fuel: Gasoline"
list_of_elements = txt.split('\n')
required_text = list_of_elements[0] + ';' + list_of_elements[1] + ';' list_of_elements[2].split(':')[1] + ';' + list_of_elements[3].split(':') + ';'
file.write(required_text + '\n')
我得到随机值写所以我不能做的例子:['Number']=656473930362736其他的也一样。所以这里['Number']=scrap接收值他在网站上找到了我说过的——如何将数据转换成字典格式是一个不同的问题,这可能可以用简单的正则表达式解决——但如果没有看到一些例子,我就不能肯定。