Python:从字符串中提取数值,并为每个值添加1
字符串包含句子和数字,可以是浮点或整数。我试图给每个数字加1,然后用字符串中的新数字替换以前的数字 我写的代码只对浮点数加1,而整数保持不变Python:从字符串中提取数值,并为每个值添加1,python,python-3.x,Python,Python 3.x,字符串包含句子和数字,可以是浮点或整数。我试图给每个数字加1,然后用字符串中的新数字替换以前的数字 我写的代码只对浮点数加1,而整数保持不变 s = """helllo everyone 12 32 how 6.326 is a going? well 7.498 5.8 today Im going 3 to talk 8748 234.0 about python 3 and compare it with python 2"""
s = """helllo everyone 12 32 how 6.326 is a going?
well 7.498 5.8 today Im going 3 to talk 8748 234.0 about
python 3 and compare it with python 2"""
newstr = ''.join((ch if ch in '0123456789.' else ' ') for ch in s)
print(newstr)
listOfNumbers = [float(i) for i in newstr.split()]
#print(f'list of number= {listOfNumbers}')
new_str = s
for digit in listOfNumbers:
New_digit = digit+1
print (New_digit)
new_str = new_str.replace(str(digit),str(New_digit))
print(f'new_str = {new_str}')
完成此任务的一种方法是使用正则表达式
例1: 提取并向数值中添加1
import re
nums = re.findall(r'(\d+(?:\.\d+)?)', s)
[int(i) + 1 if i.isdigit() else float(i) + 1 for i in nums]
说明:
- 使用正则表达式将所有数值提取到
,带或不带小数点列表中
- 使用列表理解为每个数字加1,根据存在或小数点,该数字转换为
或浮点
int
这里使用的正则表达式模式提取任何单个或重复的数字,如
\d+
。此外,还有一个可选的非捕获组((?:\。\d+)
),用于捕获小数点和小数点后的任何数字,并将此组包括在原始组中,而不是其他组中
输出:
[13, 33, 7.326, 8.498000000000001, 6.8, 4, 8749, 235.0, 4, 3]
>>> ' '.join(r)
'helllo everyone 13 33 how 7.326 is a going? well 8.498000000000001 6.8 today Im going 4 to talk 8749 235.0 about python 4 and compare it with python 3'
例2: 将原始字符串中的数值替换为数值+1 下面的算法遵循与示例1中解释的相同逻辑;正在构造一个新列表,以包含字符串中更新的数值
import re
exp = re.compile(r'(\d+(?:\.\d+)?)')
r = []
for i in re.split(' |\n', s):
if re.match(exp, i):
i = int(i) + 1 if i.isdigit() else float(i) + 1
r.append(str(i))
输出:
[13, 33, 7.326, 8.498000000000001, 6.8, 4, 8749, 235.0, 4, 3]
>>> ' '.join(r)
'helllo everyone 13 33 how 7.326 is a going? well 8.498000000000001 6.8 today Im going 4 to talk 8749 235.0 about python 4 and compare it with python 3'
使用split()
将字符串拆分为项目。每个项表示一个字符串
、一个浮点
、或一个整数
。如果它是一个字符串
,我们不能将其转换为一个数字并递增。如果转换到float
成功,它仍然可能是int
,因此我们尝试转换“进一步”
代码仍然需要处理浮点舍入问题-请参阅输出
def increment_items(string):
'''Increment all numbers in a string by one.'''
items = string.split()
for idx, item in enumerate(items):
try:
repl = False
nf = float(item)
repl = nf + 1 # when we reach here, item is at least float ...
ni = int(item) # ... but might be int - so we try
repl = ni + 1 # when we reach here, item is not float, but int
items[idx] = str(repl)
except ValueError:
if repl != False:
items[idx] = str(repl) # when we reach here, item is float
return " ".join(items)
s = "helllo everyone 12 32 how 6.326 is a going?\
well 7.498 5.8 today Im going 3 to talk 8748 234.0 about\
python 3 and compare it with python 2"
print('Input:', '\n', s, '\n')
result = increment_items(s)
print('Output:', '\n', result, '\n')
输入:
helllo everyone 12 32 how 6.326 is a going? well 7.498 5.8 today Im going 3 to talk 8748 234.0 about python 3 and compare it with python 2
helllo everyone 13 33 how 7.326 is a going? well 8.498000000000001 6.8 today Im going 4 to talk 8749 235.0 about python 4 and compare it with python 3
输出:
helllo everyone 12 32 how 6.326 is a going? well 7.498 5.8 today Im going 3 to talk 8748 234.0 about python 3 and compare it with python 2
helllo everyone 13 33 how 7.326 is a going? well 8.498000000000001 6.8 today Im going 4 to talk 8749 235.0 about python 4 and compare it with python 3
这些数字是用逗号分隔的吗?@L.Papadopoulos,没有逗号。你的问题很好,但请用逗号了解更多有关该网站的信息。@ppwater,好的,我检查一下,谢谢你的指导。谢谢你明确的回答和解释,但是有没有办法不使用regex函数?@ElhamYa-我的荣幸。是的,这是可能的-但是,我应该提到使用正则表达式是解决这个问题的最佳(稳健)方法,因为
isnumeric
和isdigit
字符串函数在浮点上不起作用。对于简单/健壮的代码,我强烈建议使用正则表达式,因为它们只能显式地匹配数字字符。想想一个例子,比如12.1a
@S3DEV-是的,你是对的,我明白你的意思了。你知道我如何用新的数字替换之前的数字吗?@ElhamYa-是的。我刚刚更新了答案,加入了示例2,其中显示了如何进行替换。希望这有帮助。@S3DEV-非常感谢您的帮助解决方案。@ack谢谢您,特别是让它如此易懂的评论。@Elham-请随意投票和/或接受:)@ack-您的代码中有一点我不明白。repl的作用是什么?实际上,repl=False的含义是什么,为什么我们不能用以下语句替换它=>如果不是item.isalpha():@Elham-我的想法是:让python尝试进行转换,而不检查isalpha
,isnumeric
,isdigit
等等。出现异常的原因可能是:1)我们正在处理不表示数值的内容(repl==False
),或2)我们有表示数值但不表示整数的内容(repl==float的值)