Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将所需数据从一个文件复制到另一个文件_Python_Regex - Fatal编程技术网

在python中将所需数据从一个文件复制到另一个文件

在python中将所需数据从一个文件复制到另一个文件,python,regex,Python,Regex,我对Python还不熟悉,我有一个文件a.txt,其中包含10-15行html代码和文本。我想将与正则表达式匹配的数据从一个a.txt复制到b.txt。假设我有一行Hello“World”How“are”you,我想复制双引号之间的数据,即World和是要复制到新文件的 这就是我所做的 if x in line: p = re.compile("\"*\"") q = p.findall(line) print q 但这只是将“”(双引号)显示为输出。我想我的正则表达式有一个错误。

我对Python还不熟悉,我有一个文件
a.txt
,其中包含10-15行html代码和文本。我想将与正则表达式匹配的数据从一个
a.txt
复制到
b.txt
。假设我有一行
Hello“World”How“are”you
,我想复制双引号之间的数据,即
World
是要复制到新文件的

这就是我所做的

if x in line:
  p = re.compile("\"*\"")
  q = p.findall(line)
  print q
但这只是将“”(双引号)显示为输出。我想我的正则表达式有一个错误。 非常感谢您的帮助。 谢谢。

您的正则表达式(在没有所有字符串转义的情况下转换为“*”
)匹配零个或多个引号,后跟一个引号

你想要

p = re.compile(r'"([^"]*)"')
说明:

"     # Match a quote
(     # Match and capture the following:
[^"]* # 0 or more characters except quotes
)     # End of capturing group
"     # Match a quote
这假设您永远不必处理转义引号,例如。g

He said: "The board is 2\" by 4\" in size"

捕获您感兴趣的组(即引号之间),从每行中提取匹配项,然后每行将它们写入新文件,例如:

import re

with open('input') as fin, open('output', 'w') as fout:
    for line in fin:
        matches = re.findall('"(.*?)"', line)
        fout.writelines(match + '\n' for match in matches)

非常感谢您这么快回复