Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.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_Spacing_Punctuation - Fatal编程技术网

Python 间距和图案替换

Python 间距和图案替换,python,spacing,punctuation,Python,Spacing,Punctuation,问题分为两部分: 第1部分 若要删除多个空格,段落将仅打断为一个空格 当前代码: import re # Read inputfile with open('input.txt', 'r') as file : inputfile = file.read() # Replace extras spaces with single space. #outputfile = re.sub('\s+', ' ', inputfile).strip() outputfile = ' '.join(

问题分为两部分:

第1部分

若要删除多个空格,段落将仅打断为一个空格

当前代码:

import re
# Read inputfile
with open('input.txt', 'r') as file :
  inputfile = file.read()

# Replace extras spaces with single space.
#outputfile = re.sub('\s+', ' ', inputfile).strip()
outputfile = ' '.join(inputfile.split(None))

# Write outputfile
with open('output.txt', 'w') as file:
  file.write(outputfile)
第二部分:

import re
# Read inputfile
with open('input.txt', 'r') as file :
  inputfile = file.read()

# Replace extras spaces with single space.
#outputfile = re.sub('\s+', ' ', inputfile).strip()
outputfile = ' '.join(inputfile.split(None))

# Write outputfile
with open('output.txt', 'w') as file:
  file.write(outputfile)
一旦多余的空间被移除;我搜索并替换模式错误

比如:'['到'['

Pattern1 = re.sub(' [ ', ' [', inputfile)
这会引发一个错误:

raise错误,v#表达式无效 错误:正则表达式意外结束

尽管如此,这是有效的…(例如:将连字符前后的单词连接在一起)

在间距问题解决后,我有很多情况需要处理标点问题

我不希望模式查看以前的模式结果的输出并进一步移动


是否有更好的方法将标点符号周围的空格切得恰到好处。

对于第一部分,您可以将标点符号按换行块拆分,压缩每一行,然后在换行时将其重新连接,如下所示:

import re
text = "\n".join(re.sub(r"\s+", " ", line) for line in re.split("\n+", text))
print(text)
import re
text = re.sub("\[ ", "[", text)
text = re.sub(" ]", "]", text)
print(text)
对于第二部分,您需要转义
[
,因为它是一个正则元字符(用于定义字符类),如下所示:

import re
text = "\n".join(re.sub(r"\s+", " ", line) for line in re.split("\n+", text))
print(text)
import re
text = re.sub("\[ ", "[", text)
text = re.sub(" ]", "]", text)
print(text)
请注意,您不需要转义
]
,因为它与
[
不匹配,因此在本上下文中并不特殊


或者对于第二部分,
text=text.replace(“[”,“[”).replace(“]”,“])
,因为您甚至不需要正则表达式。

当您要做的是简单的字符串替换时,为什么要使用regex find and replace?字符
[
在正则表达式中有一个含义,在
-
中也是如此。是的,你是对的。可以使用str replace。但是,速度方面,哪个更快?通常正则表达式的速度较慢(在大多数编程语言中)。请参阅: