码迷,mamicode.com
首页 > 编程语言 > 详细

Python逐行读取txt文本,按符合分割词并逐行写入txt

时间:2018-07-24 17:47:59      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:ace   图片   pyc   div   strong   image   pytho   文件   str   



背景Background:
我的txt文件里面存放的是搜索词,由于原始的query(搜索词)都是用/或者、来分割词,而我要达到的是每个词语是单独的一行,并且写入txt

第一步:按行读取txt文件
s = []
f  = open(‘querylist.txt‘,‘r‘) #由于我使用的pycharm已经设置完了路径,因此我直接写了文件名
for lines in f:
    # query_list.append(line.replace(‘/‘,‘‘).replace(‘、‘,‘‘).replace(‘ ‘,‘‘).strip(‘\n‘))
    ls = lines.strip(‘\n‘).replace(‘ ‘,‘‘).replace(‘、‘,‘/‘).replace(‘?‘,‘‘).split(‘/‘)
    for i in ls:
        s.append(i)
f.close()
print(s)
第二步:逐行写入txt
把我们列表中s的每一个元素写入tet,一个元素为一行,方法有很多,我这里只列举一种
(提前在你的文件路径中建立好一个空的txt:query_result)
f1 = open(‘query_result.txt‘,‘w‘)
for j in s:
    f1.write(j+‘\n‘)
f1.close()

  大功告成,最后我输出的结果是:

技术分享图片

 

Python逐行读取txt文本,按符合分割词并逐行写入txt

标签:ace   图片   pyc   div   strong   image   pytho   文件   str   

原文地址:https://www.cnblogs.com/candy3026/p/9360532.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!