我正在构建一个用于练习的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美元的价格购买了一艘船并且很棒#34;
它将分配' 5000'到一个变量,然后我将通过我的转换器
最好的方法是什么?
(希望有足够的信息,但如果人们感到困惑,我会添加更多信息)
答案 0 :(得分: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']
OR
>>> s = "I bought a boat for $5000 and it's awesome"
>>> [i[1:] for i in s.split() if i.startswith('$')]
['5000']
答案 1 :(得分: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']