1

我正在构建一个用于练习的 reddit 机器人,将美元转换为其他常用货币,并且我已经设法让转换部分正常工作,但现在我在尝试传递直接跟随美元的字符时有点卡住了签到转换器。

这就是我希望它的工作方式:

def run_bot():
    subreddit = r.get_subreddit("randomsubreddit")
    comments = subreddit.get_comments(limit=25)
    for comment in comments:
        comment_text = comment.body
        #If comment contains a string that starts with '$'
            # Pass the rest of the 'word' to a variable

例如,如果它正在处理这样的评论:

“我花了 5000 美元买了一艘船,太棒了”

它将'5000'分配给一个变量,然后我将通过我的转换器

最好的方法是什么?

(希望这是足够的信息,但如果人们感到困惑,我会添加更多)

4

2 回答 2

2

你可以使用re.findall函数。

>>> import re
>>> re.findall(r'\$(\d+)', "I bought a boat for $5000 and it's awesome")
['5000']
>>> re.findall(r'\$(\d+(?:\.\d+)?)', "I bought two boats for $5000  $5000.45")
['5000', '5000.45']

或者

>>> s = "I bought a boat for $5000 and it's awesome"
>>> [i[1:] for i in s.split() if i.startswith('$')]
['5000']
于 2015-04-16T05:18:51.440 回答
0

如果您以浮点数处理价格,则可以使用以下命令:

import re

s = "I bought a boat for $5000 and it's awesome"

matches = re.findall("\$(\d*\.\d+|\d+)", s)
print(matches) # ['5000']

s2 = "I bought a boat for $5000.52 and it's awesome"
matches = re.findall("\$(\d*\.\d+|\d+)", s2)
print(matches) # ['5000.52']
于 2015-04-16T05:23:32.777 回答