Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/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 如何为没有参数的案例实现str.split_Python_Regex_Split - Fatal编程技术网

Python 如何为没有参数的案例实现str.split

Python 如何为没有参数的案例实现str.split,python,regex,split,Python,Regex,Split,Python在没有分隔符的情况下是否使用正则表达式拆分 我无法查看str.\uuu文件\uuuu,此处也无法查看,因为split是str类型的函数(尽管它是内置的) 例如,'a\t\t\tb'>['a','b'] 背景 我正在考虑用一个空格替换所有相邻的空格,用于性能至关重要的许多文件,尽管我想知道正则表达式拆分是否足够快:也许内置的方法显示了更好的方式。首先,str内置在python中,这意味着要查看str.split的源代码,您必须深入研究它的定义位置 现在,谈谈你的实际问题。我有一种感觉,

Python在没有分隔符的情况下是否使用正则表达式拆分

我无法查看
str.\uuu文件\uuuu
,此处也无法查看,因为
split
str
类型的函数(尽管它是内置的)

例如,
'a\t\t\tb'>['a','b']

背景
我正在考虑用一个空格替换所有相邻的空格,用于性能至关重要的许多文件,尽管我想知道正则表达式拆分是否足够快:也许内置的方法显示了更好的方式。

首先,
str
内置在python中,这意味着要查看
str.split
的源代码,您必须深入研究它的定义位置

现在,谈谈你的实际问题。我有一种感觉,
re.sub
将不仅仅是杀伤力过大,而且比使用内置str.split还要慢(完全公开:我没有时间数据来支持这一点,这只是我的一种感觉)

现在,默认情况下,
str.split
在空白处拆分(它使用一个可选的参数,可用于指定要拆分的字符)。它还可以拆分任意数量的连续空白字符。现在,这意味着,如果您有一个包含空格字符的字符串,那么对该字符串调用
str.split
,将返回一个非空子字符串列表,其中没有一个包含任何空格。因此,如果字符串具有异构的连续空白字符,则这些空白字符的处理方式彼此没有区别

以下是几个例子:

In [31]: s = 'hello world'  # one space

In [32]: s.split()
Out[32]: ['hello', 'world']

In [33]: s = 'hello \tworld'  # multiple consecutive whitespace characters

In [34]: s.split()
Out[34]: ['hello', 'world']

In [35]: s = 'hello\tworld'  # a different whitespace character

In [36]: s.split()
Out[36]: ['hello', 'world']

In [37]: s = 'hello\t\tworld'  # multiple consecutive tab characters

In [38]: s.split()
Out[38]: ['hello', 'world']

In [39]: s = 'hello  world'  # multiple consecutive space characters

In [40]: s.split()
Out[40]: ['hello', 'world']
正如你所看到的,你的空格是如何存在的其实并不重要——想想
str.split
spliting,当“至少有一个空格字符”出现时

现在,如果要用一个空格替换所有连续的空白字符,可以使用
str.split
str.join

In [41]: ' '.join(['hello', 'world'])  # join the strings 'hello' and 'world' with a space between them
Out[41]: 'hello world'

In [42]: s = 'hello  world'  # notice two spaces between 'hello' and 'world'

In [43]: ' '.join(s.split())
Out[43]: 'hello world'  # notice only one space between 'hello' and 'world'

它不使用正则表达式,而是使用
iswspace(…)

我们可以在这里看到它使用了宏STRINGLIB_ISSPACE(…)


这里定义为wctypes.h的iswspace:

实际上,我终于找到了。这是一个很好的C函数,可以进行拆分。我想说,这是一个很好的介绍。拆分和连接比用C进行就地替换要差,不是吗?是否有任何C函数可以使用(甚至如何使用?)而无需数据来备份?我还怀疑split会比正则表达式更好。@PascalvKooten:我不敢猜测如何使用C来实现它,尽管我可以为您提供具有最佳运行时的算法伪代码(假设字符串实现为以null结尾的数组)。如果这是你想要的,请告诉我,我也会发布这样的解决方案