我想在python中分割字符串。
样本字符串:
嗨,我是ACT I,第1和第2幕,这是ACT II,第1和第2幕及更多。
列入下列清单:
['Hi this is', 'ACT I. SCENE 1', 'and', 'SCENE2', 'and this is', 'ACT II. SCENE 1',
 'and' , 'SCENE 2', 'and more']有人能帮我建战壕吗?我建造的是:
(ACT [A-Z]+.\sSCENE\s[0-9]+)]?(.*)(SCENE [0-9]+)但这是不正常的。
发布于 2019-11-07 07:21:39
如果我正确理解您的需求,您可以使用以下模式:
(?:ACT|SCENE).+?\d+|\S.*?(?=\s?(?:ACT|SCENE|$))演示。
分解:
(?:                    # Start of a non-capturing group.
    ACT|SCENE          # Matches either 'ACT' or 'SCENE'.
)                      # Close the non-capturing group.
.+?                    # Matches one or more characters (lazy matching).
\d+                    # Matches one or more digits.
|                      # Alternation (OR).
\S                     # Matches a non-whitespace character (to trim spaces).
.*?                    # Matches zero or more characters (lazy matching).
(?=                    # Start of a positive Lookahead (i.e., followed by...).
    \s?                # An optional whitespace character (to trim spaces).
    (?:ACT|SCENE|$)    # Followed by either 'ACT' or 'SCENE' or the end of the string.
)                      # Close the Lookahead.Python示例:
import re
regex = r"(?:ACT|SCENE).+?\d+|\S.*?(?=\s?(?:ACT|SCENE|$))"
test_str = "Hi this is ACT I. SCENE 1 and SCENE 2 and this is ACT II. SCENE 1 and SCENE 2 and more"
list = re.findall(regex, test_str)
print(list)输出:
['Hi this is', 'ACT I. SCENE 1', 'and', 'SCENE 2', 'and this is', 'ACT II. SCENE 1', 'and', 'SCENE 2', 'and more']发布于 2019-11-07 07:14:47
下面是一个工作脚本,尽管有点麻烦:
inp = "Hi this is ACT I. SCENE 1 and SCENE 2 and this is ACT II. SCENE 1 and SCENE 2 and more"
parts = re.findall(r'[A-Z]{2,}(?: [A-Z0-9.]+)*|(?![A-Z]{2})\w+(?: (?![A-Z]{2})\w+)*', inp)
print(parts)这些指纹:
['Hi this is', 'ACT I. SCENE 1', 'and', 'SCENE 2', 'and this is', 'ACT II. SCENE 1',
 'and', 'SCENE 2', 'and more']对regex逻辑的解释,该逻辑使用替换来匹配以下两种情况中的一种:
[A-Z]{2,}              match TWO or more capital letters
(?: [A-Z0-9.]+)*       followed by zero or more words, consisting only of
                       capital letters, numbers, or period
|                      OR
(?![A-Z]{2})\w+        match a word which does NOT start with two capital letters
(?: (?![A-Z]{2})\w+)*  then match zero or more similar terms发布于 2019-11-07 13:24:42
您可以使用re.findall
import re
s = 'Hi this is ACT I. SCENE 1 and SCENE 2 and this is ACT II. SCENE 1 and SCENE 2 and more'
new_s = list(map(str.strip, re.findall('[A-Z\d\s\.]{2,}|^[A-Z]{1}[a-z\s]+|[a-z\s]+', s)))输出:
['Hi this is', 'ACT I. SCENE 1', 'and', 'SCENE 2', 'and this is', 'ACT II. SCENE 1', 'and', 'SCENE 2', 'and more']https://stackoverflow.com/questions/58743530
复制相似问题