Python TextBlob翻译问题
我正在用Python、TextBlob和NLTK做一个快速情绪分析控制台应用程序 目前我正在使用一个指向西班牙语维基文章的链接,所以我不需要翻译它,我可以使用nltk西班牙语停止词列表,但是如果我想让这段代码适用于不同的语言链接,该怎么办 如果我使用下面的Python TextBlob翻译问题,python,nltk,sentiment-analysis,textblob,Python,Nltk,Sentiment Analysis,Textblob,我正在用Python、TextBlob和NLTK做一个快速情绪分析控制台应用程序 目前我正在使用一个指向西班牙语维基文章的链接,所以我不需要翻译它,我可以使用nltk西班牙语停止词列表,但是如果我想让这段代码适用于不同的语言链接,该怎么办 如果我使用下面的textfail=textfail.translate(to=“es”)行textfail=TextBlob(texto)(下面的代码),我会收到一个错误,因为它无法将西班牙语翻译成西班牙语 我可以通过使用try/catch来防止这种情况吗?有
textfail=textfail.translate(to=“es”)
行textfail=TextBlob(texto)
(下面的代码),我会收到一个错误,因为它无法将西班牙语翻译成西班牙语
我可以通过使用try/catch来防止这种情况吗?有没有一种方法可以让代码尝试翻译成不同的语言(以及使用不同的停止词列表),这取决于im提供给应用程序的链接的语言
import nltk
nltk.download('stopwords')
from nltk import word_tokenize
from nltk.corpus import stopwords
import string
from textblob import TextBlob, Word
import urllib.request
from bs4 import BeautifulSoup
response = urllib.request.urlopen('https://es.wikipedia.org/wiki/Valencia')
html = response.read()
soup = BeautifulSoup(html,'html5lib')
text = soup.get_text(strip = True)
tokens = word_tokenize(text)
tokens = [w.lower() for w in tokens]
table = str.maketrans('', '', string.punctuation)
stripped = [w.translate(table) for w in tokens]
words = [word for word in stripped if word.isalpha()]
stop_words = set(stopwords.words('spanish'))
words = [w for w in words if not w in stop_words]
with open('palabras.txt', 'w') as f:
for word in words:
f.write(" " + word)
with open('palabras.txt', 'r') as myfile:
texto=myfile.read().replace('\n', '')
textFinal=TextBlob(texto)
print (textFinal.sentiment)
freq = nltk.FreqDist(words)
freq.plot(20, cumulative=False)
请看一下包装。您可以检查正在输入的页面的语言,如果页面语言与翻译语言匹配,则跳过翻译。如下所示:
import string
import urllib.request
import nltk
from bs4 import BeautifulSoup
from langdetect import detect
from nltk import word_tokenize
from nltk.corpus import stopwords
from textblob import TextBlob, Word
nltk.download("stopwords")
# nltk.download("punkt")
response = urllib.request.urlopen("https://es.wikipedia.org/wiki/Valencia")
html = response.read()
soup = BeautifulSoup(html, "html5lib")
text = soup.get_text(strip=True)
lang = detect(text)
tokens = word_tokenize(text)
tokens = [w.lower() for w in tokens]
table = str.maketrans("", "", string.punctuation)
stripped = [w.translate(table) for w in tokens]
words = [word for word in stripped if word.isalpha()]
stop_words = set(stopwords.words("spanish"))
words = [w for w in words if w not in stop_words]
with open("palabras.txt", "w", encoding="utf-8") as f:
for word in words:
f.write(" " + word)
with open("palabras.txt", "r", encoding="utf-8") as myfile:
texto = myfile.read().replace("\n", "")
textFinal = TextBlob(texto)
translate_to = "es"
if lang != translate_to:
textFinal = textFinal.translate(to=translate_to)
print(textFinal.sentiment)
freq = nltk.FreqDist(words)
freq.plot(20, cumulative=False)
这是有用的。我想我可以设置一个条件来更改停止字列表语言。非常感谢。没问题,你们有一个有趣的项目。您在原始问题中提到,您希望将翻译行包装在try-catch块中,这也可以,但是当您提到其他语言时,似乎langdetect会有所帮助。