python - 如何从 pastebin.com 获取多个句子并将它们放入列表中?
问题描述
所以我在这里有这个 pastebin 链接https://pastebin.com/raw/vxGkayKY我想要一种让 python 获取句子和响应并将它们放在列表中的方法。有没有办法做到这一点?
例如:
list = [
'This is my first sentence.\nHere\'s a response for it.',
'Here\'s another sentence.\nHere\'s another response.',
'Here\'s the third sentence.\nHere\'s another response.'
]
我正在尝试使python代码使用随机选择一个句子random.choice(list)
例如,输出将是(忽略 #):
#This is my first sentence.
#Here's a response for it.
有没有办法做到这一点?任何帮助表示赞赏。谢谢。
解决方案
Try this:
import requests
import random
req = requests.get('https://pastebin.com/raw/vxGkayKY')
lines = req.text.strip().replace('\r','').split('\n\n')
choice = random.choice(lines)
print(choice)
As a side-note, it's bad style to overwrite keywords like list
with a variable since you might need them later on.