Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.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_String_File_Parsing - Fatal编程技术网

Python 解析所有空格和语法

Python 解析所有空格和语法,python,regex,string,file,parsing,Python,Regex,String,File,Parsing,我想创建一个Python解析器,用于解析文件中的空白和语法。我要做的是读取一个文件,并将每个空格、标点符号和单词放入列表中它自己的元素中。到目前为止,我已经完成了以下拆分空白的步骤: with open(fname, 'r') as f: words = re.split("(\s+)", f.read()) withwords保存文件内容列表,每个空格作为其自己的元素。但是,我在分析标点符号时遇到了问题,因为列表元素可能包含像“Hello”这样的项目,并且元素中带有引号。相反,我希望它看

我想创建一个Python解析器,用于解析文件中的空白和语法。我要做的是读取一个文件,并将每个空格、标点符号和单词放入列表中它自己的元素中。到目前为止,我已经完成了以下拆分空白的步骤:

with open(fname, 'r') as f:
  words = re.split("(\s+)", f.read())
with
words
保存文件内容列表,每个空格作为其自己的元素。但是,我在分析标点符号时遇到了问题,因为列表元素可能包含像
“Hello”
这样的项目,并且元素中带有引号。相反,我希望它看起来是这样的:

list = ['"', 'Hello', '"', '@', 'World'] 
与之相反:

list = ['"Hello"', '@World']

如果有人能帮我,那就太好了

您可以使用re.findall来代替拆分

import re

string = '"hello" @world'
L = re.findall(r'(\w+|[@"])', string)
print(L)
#['"', 'hello', '"', '@', 'world'] 

我以为edi_allen拥有它,但后来发现使用findall时,空白区域没有进入列表

with open(fname, 'r') as f:
  words = re.split('(["\'@&,;:\(\)\s+\*\?\.]|\w+)', f.read())

#because each list element is separated from the next by an empty string:
while '' in words:
    words.remove('')    
print (words)           
给定包含以下内容的文本文件:

布莱恩:他们会对我做什么

本:哦,你可能会被钉死在十字架上

布莱恩:钉十字架

本:是的,初犯

返回的列表为:

>>>  ['BRIAN', ':', ' ', 'What', ' ', 'will', ' ', 'they', ' ', 
'do', ' ', 'to', ' ', 'me', '?', '\n', 'BEN', ':', ' ', 'Oh', ',', ' ',
'you', "'", 'll', ' ', 'probably', ' ', 'get', ' ', 'away', ' ',
'with', ' ', 'crucifixion', '.', '\n', 'BRIAN', ':', ' ',
'Crucifixion', '?', '!', '\n', 'BEN', ':', ' ', 'Yeah', ',', ' ',
'first', ' ', 'offence', '.', ' ', '\n']

\s
表示空白。如果您想在其他方面进行拆分,则必须将其添加到拆分正则表达式中。e、 g.
[\s“@]
如果可能的话,我想把“'@all作为元素@马尔克