我正面临着在python中csv文件中"header“重复的问题。当我执行代码时,我得到了另一个我想要的csv文件,所以它在正确的路径上,但问题在它内部,我在下面的结果中显示了它:
import csv
with open('url.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
url=row['URL']
no_dots= url.count(".")
no_per= url.count("%")
no_dash= url.count("-")
no_under= url.count("_")
no_equal= url.count("=")
no_question=url.count("?")
no_colon=url.count(":")
no_ampper=url.count("&")
no_hash=url.count("#")
no_dollar=url.count("$")
no_atrate=url.count("@")
no_exla=url.count("!")
no_star=url.count("*")
no_plus=url.count("+")
no_hiphen=url.count("-")
no_xor=url.count("^")
no_slash=url.count("/")
no_less=url.count("<")
no_greater=url.count(">")
with open('features.csv', 'a') as csvfile:
fieldnames = ['dots', 'per','dash','under','equal','question','colon','ampper','hash','dollar','atrate','exla','star',
'plus','hiphen','xor','slash','less','greater','URL']
writer = csv.DictWriter(csvfile,fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'dots': no_dots, 'per': no_per,'dash':no_dash,'under':no_under,
'equal': no_equal, 'question': no_question, 'colon': no_colon , 'ampper': no_ampper, 'hash': no_hash, 'dollar': no_dollar, 'atrate': no_atrate,
'exla': no_exla, 'star': no_star , 'plus': no_plus,'hiphen': no_hiphen, 'xor': no_xor, 'slash': no_slash, 'less': no_less, 'greater': no_greater,
'URL':url}
我期望得到这样的结果:
dots per dash under equal question colon ampper hash....url
1 0 0 0 1 1 1 0 0
https://stackoverflow.com/questions/ask?guided=true
但是我一次又一次地为每个url重复标题的结果,并且我的数据集中有超过50000个url……请帮我弄一下代码。提前谢谢。
发布于 2019-03-25 12:14:33
import os
out_file = '/path/to/my/features.csv'
if not os.path.isfile(out_file):
writer.writeheader()
writer.writerow({'
else:
writer.writerow({'
你在'a‘追加模式下打开你的out文件/dict,所以检查文件是否存在,如果不存在,写下标题和行,如果存在,只写一行。HTH
https://stackoverflow.com/questions/55327098
复制相似问题