python - 修复最大匹配算法,同时使用 ntlk 标记低资源语言
问题描述
我正在努力标记一种低资源语言,但是在运行程序时我得到了一个外部错误的返回。这是代码:
D = ['چھی', 'معلومات', 'کا', 'بندی']
def max_match(sentence, dictionary):
if not sentence:
return ""
for i in range(len(sentence), -1, -1):
first_word = sentence[:i]
remainder = sentence[i:]
if first_word in dictionary:
return first_word + " " + max_match(remainder, dictionary)
first_word = sentence[0]
remainder = sentence[1:]
return first_word + max_match(remainder, dictionary)
print (max_match('چھیمعلوماتکا بندی'), D)
错误是SyntaxError: "return" outside function
解决方案
您的代码的问题很简单;您未能将for
循环放入函数中。你的代码应该是这样的:
D = ['چھی', 'معلومات', 'کا', 'بندی']
def max_match(sentence, dictionary):
if not sentence:
return ""
for i in range(len(sentence), -1, -1):
first_word = sentence[:i]
remainder = sentence[i:]
if first_word in dictionary:
return first_word + " " + max_match(remainder, dictionary)
first_word = sentence[0]
remainder = sentence[1:]
return first_word + max_match(remainder, dictionary)
print(max_match('چھیمعلوماتکا بندی', D))
推荐阅读
- python - 如何从另一个列表中的字符串创建列表。Python?
- python - 如何通过检查所有元素以及使整个嵌套列表小写来检查字符串是否在嵌套列表中?
- firebase - Firebase Firestore 是否在 React Native Expo 中工作?
- sql - 如何动态地将列名传递给查询?
- php - Authorize.Net Paypal Express PHP API:交易未在 Authorize.Net 中更新,也未捕获正确金额的问题
- snowflake-cloud-data-platform - 我可以使用 snowflake snowsql !spool 命令覆盖现有文件吗?
- swift - 解析 HealthKit 查询的结果
- ffmpeg - 我怎样才能插入一个空的字幕
- user-interface - 在 Tkinter 中尝试 self.after() 时,整个小部件冻结/不加载
- javascript - AngularFireMessaging - 错误 this._next 不是函数