我使用 Python 和 Tweepy 開發了一個非常基本的 Twitter 機器人。它成功地向 twitter 發布了一條推文,我可以修改這行代碼中的文本:response = client.create_tweet( text='Testing' ) 制作不同的推文
我為此使用的完整代碼是:
import tweepy
client = tweepy.Client(consumer_key="XXXXX",
consumer_secret="XXXXX",
access_token="XXXXX",
access_token_secret="XXXXX")
# Create Tweet
response = client.create_tweet(
text='Testing'
)
print(f"https://twitter.com/user/status/{response.data['id']}")
我想弄清楚的是如何撰寫一個 Bot 來隨機讀取存盤在檔案中的資料,并將其放在一起以形成一個可讀的句子或段落,有點像郵件合并的作業方式。這是一個示例,有 3 個檔案或 3 個值:
Value1
Check out this, View this, See this
Value 2
product, item, piece
Value 3
on our online shop, on our store, on our website
如果機器人能夠隨機讀取和選擇資料,它可以以任何順序從檔案或值中選擇任何資料,將它們放在一起,作為句子或段落就有意義
經過研究,我發現使用文本或 JSON 檔案可能是可能的。我遵循了 JSON 教程,并為文本和影像重新創建了一個如下所示的示例:
[
{
"text": "hi",
"image": "/image1.jpg"
},
{
"text": "hello",
"image": "/image2.jpg"
}
]
我想我已經弄清楚了如何使用以下代碼讀取 JSON 檔案:
import json
with open(r"C:\Users\Administrator\Desktop\Python\test.json") as f:
info = json.load(f)
randomChoice = random.randrange(len(info))
print (info[randomChoice])
我真正苦苦掙扎的是實作這一目標的最佳方法,以及如何創建代碼來發布使用它選擇的隨機資料制定的推文
到目前為止,我嘗試將 Tweepy 和從 JSON 檔案中讀取資料的能力結合起來,但我無法讓它作業,因為我不知道如何將它讀入的資料發布到 Twitter :
import tweepy
import random
import json
with open(r"C:\Users\Administrator\Desktop\Python\test.json") as f:
info = json.load(f)
client = tweepy.Client(consumer_key="XXXXX",
consumer_secret="XXXXX",
access_token="XXXXX",
access_token_secret="XXXXX")
# Create Tweet
randomChoice = random.randrange(len(info))
print (info[randomChoice])
response = client.create_tweet(
text='NOT SURE HOW TO CODE THIS PART SO TWEEPY POSTS RANDOMLY SELECTED DATA'
print(f"https://twitter.com/user/status/{response.data['id']}")
我是 Python 和 Tweepy 的新手,所以只有很少的了解,但非常感謝任何幫助
uj5u.com熱心網友回復:
關于存盤:
您可以讀取檔案并使用該split(",")方法決議每一行,但 JSON 可能是最好的解決方案,因為它已經格式化。
您想要一個替代串列(它們是字串串列),那么為什么不簡單地使用串列串列呢?
你的 JSON 檔案會是這樣的:
[
["Check out this", "View this", "See this"],
["product", "item", "piece"],
["on our online shop", "on our store", "on our website"]
]
關于您的 Python 代碼:
您不需要生成隨機索引來選擇串列中的元素:
randomChoice = random.randrange(len(info))
print (info[randomChoice])
隨機模塊可以為您完成:
random.choice(info)
關于造句:
您現在可以跨過主串列,從每個備選串列中選擇一個備選并將其添加到您將發布的句子中:
full_sentence = ""
for alternatives in data:
selected_alternative = random.choice(alternatives)
full_sentence = ' ' selected_alternative
最終代碼:
import json
import random
# You can start by loading the JSON file
with open(r"test.json") as f:
data = json.load(f)
# You can then build your full sentence
full_sentence = ""
for alternatives in data:
selected_alternative = random.choice(alternatives)
full_sentence = ' ' selected_alternative
# You can now post your full sentence on Twitter
client = tweepy.Client(consumer_key="XXXXX", ...)
response = client.create_tweet(text=full_sentence)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/465852.html
