gpt4 book ai didi

python - 尝试使用 Python 将字符串拆分为多个部分

转载 作者:太空宇宙 更新时间:2023-11-04 09:12:20 25 4
gpt4 key购买 nike

我正在尝试按以下方式拆分字符串。这是一个示例字符串:

"Hello this is a string.-2.34 This is an example1 string."

请注意“”为U+F8FF unicode字符,字符串类型为Unicode。

我想将字符串打断为:

"Hello this is a string.","-2.34"," This is an example1 string."

我已经编写了一个正则表达式来拆分字符串,但是使用它我无法获得我想要的数字部分。 (第一个字符串为 -2.34)

我的代码:

import re
import os
from django.utils.encoding import smart_str, smart_unicode

text = open(r"C:\data.txt").read()
text = text.decode('utf-8')
print(smart_str(text))

pat = re.compile(u"\uf8ff-*\d+\.*\d+")
newpart = pat.split(text)
firstpart = newpart[::1]

print ("first part of the string ----")
for f in firstpart:
f = smart_str(f)
print ("-----")
print f

最佳答案

如果你想将它保留在 re.split 的结果中,你需要在 -*\d+\.*\d+ 周围加上括号:

import re
text = u"Hello this is a string.\uf8ff-2.34 This is an example1 string."
print(re.split(u'\uf8ff(-*\d+\.*\d+)', text))

产量

[u'Hello this is a string.', u'-2.34', u' This is an example1 string.']

关于python - 尝试使用 Python 将字符串拆分为多个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13436965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com