我正在学习python,然后我遇到以下困难。 我想要清理的文件是.csv文件。 包含必须从.csv文件中删除的单词的文件是.txt .txt文件是域名列表:
domain.com
domain2.com
domain3.com
.csv文件是一个配置文件,如下所示:
domain.com;8;Started;C:\inetpub\wwwroot\d\domain.com;"http *:80:www.domain.com"
如果.txt文件包含" domain.com"我希望删除上面的完整行。 如果一些python忍者可以解决这个问题,我会非常感激。(或者在bash中?)
答案 0 :(得分:2)
这样就够了吗?
import sys
def main():
with open(sys.argv[1]) as fh:
fhDomains = fh.read().split(";")
with open(sys.argv[2]) as fh:
fhExcludes = fh.read().split("\n")
for i, dom in enumerate(fhDomains):
if dom in fhExcludes:
del fhDomains[i]
fh = open(sys.argv[1], "w")
fh.write(";".join(fhDomains))
if __name__ == "__main__":
main()
执行:
script.py Domains.txt excludes.txt
答案 1 :(得分:2)
尝试:
grep -vf <(sed 's/.*/^&;/' domains.txt) file.csv
@glenn jackman的建议 - 更短。
grep -wFvf domains.txt file.csv
但是,域名中的foo.com
将匹配两行(一个不需要的行),例如:
foo.com;.....
other.foo.com;.....
...洙
我的domains.txt
dom1.com
dom3.com
我的file.csv(只需要第一列)
dom1.com;wedwedwe
dom2.com;wedwedwe 2222
dom3.com;wedwedwe 333
dom4.com;wedwedwe 444444
结果:
dom2.com;wedwedwe 2222
dom4.com;wedwedwe 444444
如果您有Windows文件 - 这些行不仅以\r\n
结尾\n
,请使用:
grep -vf <(<domains.txt tr -d '\r' |sed -e 's/.*/^&;/') file.csv
答案 2 :(得分:2)
好吧,因为OP正在学习python ......
$ python SCRIPT.py
TXT_file = 'TXT.txt'
CSV_file = 'CSV.csv'
OUT_file = 'OUTPUT.csv'
## From the TXT, create a list of domains you do not want to include in output
with open(TXT_file, 'r') as txt:
domain_to_be_removed_list = []
## for each domain in the TXT
## remove the return character at the end of line
## and add the domain to list domains-to-be-removed list
for domain in txt:
domain = domain.rstrip()
domain_to_be_removed_list.append(domain)
with open(OUT_file, 'w') as outfile:
with open(CSV_file, 'r') as csv:
## for each line in csv
## extract the csv domain
for line in csv:
csv_domain = line.split(';')[0]
## if csv domain is not in domains-to-be-removed list,
## then write that to outfile
if (not csv_domain in domain_to_be_removed_list):
outfile.write(line)
答案 3 :(得分:0)
这个awk
单行应该可以解决问题:
awk -F';' 'NR == FNR {a[$1]++; next} !($1 in a)' txtfile csvfile