[英]How to account for special characters when splitting string in python
我有幾個“[一個或多個單詞] [數字] [一個或多個單詞]”形式的字符串,我想將它們分成兩個字符串和數字。 例如,如果字符串是:
"A sample string 20 something"
我想獲得:
str1 = "A sample string"
numb = 20
str2 = 'something'
我已經(幾乎)使用以下代碼實現了我的目標:
for s in row.split():
if s.isdigit():
quants = s
temp = row.split("{}".format(quants))
str1 = temp[0].strip()
str2 = temp[1].strip()
這適用於大多數情況。 但是,有兩個我無法處理的異常:
如果數字在括號內,我希望它被計為一個字符串。 例如:
“一些文字(僅作為 1 個示例)還有 2 個單詞”
我想要 str1 =“一些文本(僅作為 1 個示例)”
有時數字以特殊字符(Unicode?)、¼、½ 和 ¾ 表示。 我該如何解釋這些?
我懷疑答案是使用正則表達式而不是分隔符,但我還不能真正掌握如何使用它們。
您可以使用帶有 3 個捕獲組的正則表達式,然后獲取這些組的值。
^(\w+(?: \w+)*(?: \([^()]*\))?) (\d+|[¼½¾]) (\w+(?: \w+)*)$
解釋
^
字符串開頭(
捕獲組 1
\w+(?: \w+)*
匹配 1+ 個單詞字符,可選地以空格和 1+ 個單詞字符重復(?: \([^()]*\))?
可選地匹配空格並形成左括號直到右括號)
關閉組並匹配空間(\d+|[¼½¾])
捕獲組 2匹配 1+ 個數字或列出的¼½¾
和空格中的 1 個(\w+(?: \w+)*)
捕獲組 3匹配 1+ 個單詞字符,並可選擇重復前面的空格$
字符串結尾示例代碼
import re
regex = r"(\w+(?: \w+)*(?: \([^()]*\))?) (\d+|[¼½¾]) (\w+(?: \w+)*)"
s = "Some text (just as 1 example) ¼ more words"
match = re.match(regex, s)
if match:
print(match.group(1))
print(match.group(2))
print(match.group(3))
Output
Some text (just as 1 example)
¼
more words
一個更廣泛的模式,它使用.*
來匹配除換行符以外的任何字符,而不是使用\w+
^(.*(?:\([^()]*\))?) (\d+|[¼½¾]) (.+)
我通過用數字替換正則表達式來調整這個答案
import re
l = re.compile("((?<=\d)(?=\D)|(?=\d)(?<=\D))(?![^\(]*\))").split(test)
給了我這個:
['A sample string ', '20', ' something']
在這里測試: https://regex101.com/r/zT2dF9/53
其中 as ((?<=\d)(?=\D)|(?=\d)(?<=\D))
可以分為兩個步驟: (?<=\d)(?=\D ) 是數字的后視(由(?<=\d)
完成),后跟任何類型的非數字 `(?=\D)'
反之亦然(?=\d)(?<=\D)
搜索非數字后跟數字
這由(?![^\(]*\))
連接以忽略括號中的內容
有關正則表達式文字的詳細信息,請查看: https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.