Board logo

标题: [问题求助] Python怎么去掉文本中的引号 [打印本页]

作者: netdzb    时间: 2019-7-12 15:34     标题: Python怎么去掉文本中的引号

raw文本的内容如下:

"寻找·李慧珍"
"欲望敦煌"
"寻找李慧珍"
"远行"
"蓝色魔力"
"距离
"自由的味道"
"珍重"
"咖啡时间"
"幸福的眼泪"
"My Way"

-----------------------------

# -*- coding: UTF-8 -*-
f = open("raw.txt")             # 返回一个文件对象
line = f.readline()                # 调用文件的 readline()方法
while line:
    line = f.readline()
    print line[1:-1]                # 这样好像不大行
f.close(
作者: cfwyy77_bat    时间: 2019-7-12 17:48

本帖最后由 cfwyy77_bat 于 2019-7-12 17:56 编辑

如果 每行都是有规则的引号(你的示例样本 有 一行最后没有引号的)
那你用这切片的方法应该可以的。  line[1:-2] 这样切应该可以的。  不过你这样的写法有点问题的。

可以参考一下我写的
  1. with open("1.txt","r",encoding="utf-8") as f:
  2.     for line in f:
  3.         print(line[1:-2])
复制代码
不过这种需求不指定python的话,还是sed好,一行完事。
作者: codegay    时间: 2019-7-12 21:31

用re findall直接返回一个list
  1. import re
  2. with open("test.txt", encoding="utf-8") as f:
  3.     txt = f.read()
  4.     result = re.findall("""\"(.*?)\"""",txt)
  5. print(result)
复制代码

作者: codegay    时间: 2019-7-13 00:01

python 字符串方法里有strip和rstrip,lstrip这些方法可以脱掉字符串里指定的字符。
作者: netdzb    时间: 2019-7-13 00:21

回复 2# cfwyy77_bat

搭车问一下,如何如何用sed删除没有关键字的所有行。
假设有个文本里面有root关键字,有root的全部保留。
其余的删除。
我试了!好像不对啊。
作者: cfwyy77_bat    时间: 2019-7-15 07:31

回复 5# netdzb
  1. sed '/root/!d' file
复制代码

作者: Batcher    时间: 2019-7-15 08:23

回复 5# netdzb
  1. sed "/root/!d" 1.txt > 2.txt
复制代码
  1. sed -n "/root/p" 1.txt > 3.txt
复制代码

作者: poptang    时间: 2019-7-17 12:27

with open('123.txt','r') as f:
    with open('222.txt', 'w') as f1:
        for line in f.readlines():
            f1.write(line.replace('"',''))




欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2