我有一个数据文件(未structed凌乱的文件),从我擦洗字符串(删除字符串)的具体名单。
下面是我在做什么,但没有结果:
infile = r"messy_data_file.txt"
outfile = r"cleaned_file.txt"
delete_list = ["firstname1 lastname1","firstname2 lastname2"....,"firstnamen lastnamen"]
fin=open(infile,"")
fout = open(outfile,"w+")
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()
当我执行该文件,我得到以下错误:
NameError: name 'word' is not defined
请帮忙!
该readlines
方法返回线 ,而不是单词的列表,让你的代码只会工作的地方你的话一个是通过自身的线。
由于文件是迭代器在线路可以做到这一点很容易:
infile = "messy_data_file.txt"
outfile = "cleaned_file.txt"
delete_list = ["word_1", "word_2", "word_n"]
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()
基于您的评论:“我双击.py文件,它似乎要调用的几秒钟后消失了Python应用程序。我没有得到任何的错误思想”,我相信你的问题是脚本没有找到输入文件。 这也是为什么你没有得到任何输出。 当您双击点击它......我居然想不起解释是要去看看,但我认为这是安装了python.exe地方。
使用完全合格的路径像这样。
# Depends on your OS
infile = r"C:\tmp\messy_data_file.txt"
outfile = r"C:\tmp\cleaned_file.txt"
infile = r"/etc/tmp/messy_data_file.txt"
outfile = r"/etc/tmp/cleaned_file.txt"
另外,你的理智,在命令行而不是双击运行它。 这将是更容易捕获错误/输出。
要删除同一文件中的字符串,我用这个代码
f = open('./test.txt','r')
a = ['word1','word2','word3']
lst = []
for line in f:
for word in a:
if word in line:
line = line.replace(word,'')
lst.append(line)
f.close()
f = open('./test.txt','w')
for line in lst:
f.write(line)
f.close()
到OP,罗斯Patterson的方法上面完美的作品对我来说,即
infile = "messy_data_file.txt"
outfile = "cleaned_file.txt"
delete_list = ["word_1", "word_2", "word_n"]
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()
例:
我有一个名为messy_data_file.txt文件,其中包括以下的话(动物),不一定在同一行。 像这样:
Goat
Elephant
Horse Donkey Giraffe
Lizard
Bird
Fish
当我修改代码来读取(实际上只是增加的话,删除了“delete_list”行):
infile = "messy_data_file.txt"
outfile = "cleaned_file.txt"
delete_list = ["Donkey", "Goat", "Fish"]
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()
由此产生的“cleaned_file.txt”看起来是这样的:
Elephant
Horse Giraffe
Lizard
Bird
有一个空行,其中“喜羊羊”曾经是(其中,奇怪的是,除去“驴”没有),但对于我而言,这工作正常。
我还添加输入(“按Enter键退出...”)代码的最末端,从开口保持命令行窗口,给我一声关上时,我双击remove_text.py文件来运行它,但是请注意,你会抓住任何错误这样。
要做到这一点我在命令行中运行(其中C:\ Just_Testing是目录,我的所有文件,即remove_text.py和messy_text.txt)是这样的:
C:\Just_Testing\>py remove_text.py
要么
C:\Just_Testing>python remove_text.py
工作方式完全相同。
当然,写HTML时一样,我想从运行比你碰巧坐在,如目录之外的其他地方PY或蟒蛇时,它绝不会伤害到使用完全合格的路径:
C:\Windows\System32\>python C:\Users\Me\Desktop\remove_text.py
在代码中,当然这将是:
infile = "C:\Users\Me\Desktop\messy_data_file.txt"
outfile = "C:\Users\Me\Desktop\cleaned_file.txt"
小心使用相同的完全合格的路径,将您的新创建的cleaned_file.txt或将创建不论身在何处,并寻找它时,可能会引起混淆。
就个人而言,我有PATH中设置为指向我的环境变量所有我的Python安装即C:\ Python3.5.3,C:\ Python2.7.13等这样我就可以运行在任何地方PY或Python。
无论如何,我希望做微调调整帕特森先生这段代码可以让你正是你需要的。 :)
。