使用正则表达式使用不同的场景拆分字符串

时间:2016-10-20 20:57:58

标签: python regex python-3.x

我有两个场景,所以拆分一个字符串 方案1:

"@#$hello?? getting good.<li>hii"

我希望被分割为'hello','getting','good.<li>hii(场景1)

'hello','getting','good','li,'hi' (Scenario 2)

有什么想法吗?

4 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

>>> re.split(r"[^\w<>.]+", s) # or re.split(r"[@#$? ]+", s)
['', 'hello', 'getting', 'good.<li>hii']
>>> re.split(r"[^\w]+", s)
['', 'hello', 'getting', 'good', 'li', 'hii']

答案 1 :(得分:0)

这可能是你正在寻找\ w +它匹配任何数字或字母的次数尽可能多1到n倍。这是一个有效的Java脚本

&#13;
&#13;
var value = "@#$hello?? getting good.<li>hii";
var matches = value.match(
     new RegExp("\\w+", "gi")
);
console.log(matches)
&#13;
&#13;
&#13;

它的工作原理是使用\ w +,它尽可能多地匹配单词字符。你也可以使用[A-Za-b]来匹配不是数字的字母。如此处所示。

&#13;
&#13;
var value = "@#$hello?? getting good.<li>hii777bloop";
var matches = value.match(
     new RegExp("[A-Za-z]+", "gi")
);
console.log(matches)
&#13;
&#13;
&#13;

它尽可能多地匹配括号1到n的时间。在这种情况下,小写字符的范围a-z和A-Z uppder case字符的范围。希望这是你想要的。

答案 2 :(得分:0)

如果您正在寻找没有 regex的解决方案string.punctuation会为您提供所有特殊字符的列表。 将此列表与 list comprehension 一起使用,以获得所需的结果:

>>> import string
>>> my_string = '@#$hello?? getting good.<li>hii'
>>> ''.join([(' ' if s in string.punctuation else s) for s in my_string]).split()
['hello', 'getting', 'good', 'li', 'hii'] # desired output

说明: 以下是有关其工作原理的分步说明:

import string # Importing the 'string' module
special_char_string = string.punctuation
# Value of 'special_char_string': '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

my_string = '@#$hello?? getting good.<li>hii'

# Generating list of character in sample string with
# special character replaced with whitespace 
my_list = [(' ' if item in special_char_string else item) for item in my_string]

# Join the list to form string
my_string = ''.join(my_list)

# Split it based on space
my_desired_list = my_string.strip().split()

my_desired_list的值为:

['hello', 'getting', 'good', 'li', 'hii']

答案 3 :(得分:0)

对于第一种情况,只需使用regex查找包含单词字符和<>.的所有单词:

In [60]: re.findall(r'[\w<>.]+', s)
Out[60]: ['hello', 'getting', 'good.<li>hii']

对于第二个,只有在重复的字符不是有效的英语单词时才需要重复,你可以使用nltk语料库和re.sub正则表达式来执行此操作:

In [61]: import nltk

In [62]: english_vocab = set(w.lower() for w in nltk.corpus.words.words())

In [63]: repeat_regexp = re.compile(r'(\w*)(\w)\2(\w*)')

In [64]: [repeat_regexp.sub(r'\1\2\3', word) if word not in english_vocab else word for word in re.findall(r'[^\W]+', s)]
Out[64]: ['hello', 'getting', 'good', 'li', 'hi']