简体   繁体   English

如何替换字符串中的数字?

[英]How to replace digits in string?

Ok say I have a string in python: 好吧,我在python中有一个字符串:

str="martin added 1 new photo to the <a href=''>martins photos</a> album."

the string contains a lot more css/html in real world use 该字符串在实际使用中包含更多的css / html

What is the fastest way to change the 1 ( '1 new photo' ) to say '2 new photos' . 将1( '1 new photo' )更改为'2 new photos'的最快方法是什么。 of course later the '1' may say '12' . 当然以后, '1'可能会说'12' Note, I don't know what the number is, so doing a replace is not acceptable. 请注意,我不知道数字是多少,因此不能进行替换。 I also need to change 'photo' to 'photos' but I can just do a .replace(...) . 我还需要将'photo'更改为'photos'但是我可以做a .replace(...) Unless there is a neater, easier solution to modify both? 除非有更整洁的方法,否则不要更容易修改两者?

Update 更新资料

Never mind. 没关系。 From the comments it is evident that the OP's requirement is more complicated than it appears in the question. 从评论中可以明显看出,OP的要求比问题中要复杂的多。 I don't think it can be solved by my answer. 我认为我的答案无法解决。

Original Answer 原始答案

You can convert the string to a template and store it. 您可以将字符串转换为模板并进行存储。 Use placeholders for the variables. 将占位符用于变量。

template = """%(user)s added %(count)s new %(l_object)s to the 
      <a href='%(url)s'>%(text)s</a> album."""

options = dict(user = "Martin", count = 1, l_object = 'photo', 
      url = url, text = "Martin's album")

print template % options

This expects the object of the sentence to be pluralized externally. 这期望句子的对象在外部被复数。 If you want this logic (or more complex conditions) in your template(s) you should look at a templating engine such as Jinja or Cheetah . 如果要在模板中使用这种逻辑(或更复杂的条件),则应查看诸如JinjaCheetah的模板引擎。

since you're not parsing html, just use an regular expression 由于您没有解析html,因此只需使用正则表达式

import re

exp = "{0} added ([0-9]*) new photo".format(name)
number = int(re.findall(exp, strng)[0])

This assumes that you will always pass it a string with the number in it. 假设您将始终向其中传递带有数字的字符串。 If not, you'll get an IndexError . 如果没有,您将得到IndexError

I would store the number and the format string though, in addition to the formatted string. 除了格式化的字符串外,我还会存储数字和格式的字符串。 when the number changes, remake the format string and replace your stored copy of it. 当数字更改时,重新制作格式字符串并替换其存储的副本。 This will be much mo'bettah' then trying to parse a string to get the count. 然后尝试解析字符串以获取计数将非常麻烦。

In response to your question about the html mattering, I don't think so. 在回答有关html的问题时,我不这么认为。 You are not trying to extract information that the html is encoding so you are not parsing html with regular expressions. 您没有尝试提取html编码的信息,因此您没有使用正则表达式解析html。 This is just a string as far as that concern goes. 就此而言,这只是一个字符串。

It sounds like this is what you want (although why is another question :^) 听起来这就是您想要的(尽管为什么是另一个问题:^)

import re

def add_photos(s,n):
    def helper(m):
        num = int(m.group(1)) + n
        plural = '' if num == 1 else 's'
        return 'added %d new photo%s' % (num,plural)
    return re.sub(r'added (\d+) new photo(s?)',helper,s)

s = "martin added 0 new photos to the <a href=''>martins photos</a> album."
s = add_photos(s,1)
print s
s = add_photos(s,5)
print s
s = add_photos(s,7)
print s

Output 输出量

martin added 1 new photo to the <a href=''>martins photos</a> album.
martin added 6 new photos to the <a href=''>martins photos</a> album.
martin added 13 new photos to the <a href=''>martins photos</a> album.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM