[英]How do I get the base of a synonym/plural of a word in python?
我想使用 python 將單詞的所有同義詞和復數 forms 轉換為單詞的基本版本。
例如,嬰兒會變成嬰兒,嬰兒和嬰兒也會變成嬰兒。
我嘗試創建一個原始版本的復數到根代碼,但它的問題是它並不總是正確地 function 並且無法檢測到大量情況。
contents = ["buying", "stalls", "responsibilities"]
for token in contents:
if token.endswith("ies"):
token = token.replace('ies','y')
elif token.endswith('s'):
token = token[:-1]
elif token.endswith("ed"):
token = token[:-2]
elif token.endswith("ing"):
token = token[:-3]
print(contents)
我以前沒有使用過這個庫,所以這有點鹽。 但是,NodeBox Linguistics似乎是一組合理的腳本,如果您使用的是MacOS,它們可以完全滿足您的需求。 在此處檢查鏈接: https : //www.nodebox.net/code/index.php/Linguistics
根據他們的文檔,看起來您將能夠使用如下代碼:
print( en.noun.singular("people") )
>>> person
print( en.verb.infinitive("swimming") )
>>> swim
etc.
除了上面的示例外,還要考慮的另一個自然語言處理庫是NLTK
。 我之所以推薦使用外部庫,是因為英語有很多例外。 正如我在評論中提到的那樣,考慮一下諸如“ class”,“ fling”,“ red”,“ geese”等字樣,它們會違反原始問題中提到的規則。
我構建了一個 python 庫 - Plurals and Countable ,它在 github 上是開源的。主要目的是獲取復數(是的,某些單詞的復數),但它也解決了這個特殊問題。
import plurals_counterable as pluc
pluc.pluc_lookup_plurals('men', strict_level='dictionary')
將返回以下內容的字典。
{
'query': 'men',
'base': 'man',
'plural': ['men'],
'countable': 'countable'
}
基域就是你所需要的。
圖書館實際上是在字典中查找單詞,因此需要一些時間來請求、解析和返回。 或者,您可以使用Dictionary.video提供的 REST API。 您需要聯系 admin@dictionary.video 以獲得 API 密鑰。 電話會像
import requests
import json
import logging
url = 'https://dictionary.video/api/noun/plurals/men?key=YOUR_API_KEY'
response = requests.get(url)
if response.status_code == 200:
return json.loads(response.text)['base']
else:
logging.error(url + ' response: status_code[%d]' % response.status_code)
return None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.