我正在构建一个 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
例如,如果要查看这样的评论:
"I bought a boat for $5000 and it's awesome"
它会将“5000”分配给一个变量,然后我将其放入转换器
最好的方法是什么?
(希望这是足够的信息,但如果人们感到困惑,我会添加更多)
最佳答案
您可以使用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']
关于python - 如何返回字符串中以某个字符开头的单词? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29665859/