【问题标题】:language detection code in pythonpython中的语言检测代码
【发布时间】:2015-01-29 23:07:07
【问题描述】:

因此,我们在 python 中构建了一个语言检测程序,它只检测不同的语言。我们的代码看起来不错;没有错误,但我没有得到想要的结果。每当我在 Eclipse 上运行它时,它都会运行并终止,为我们提供运行时间和“OK”。它应该打印所写文本的语言。

def compute_ratios(text):

   tokens = wordpunct_tokenize(text)
   words = [word.lower() for word in tokens]

   langratios = {}

   for language in stopwords.fileids():
       stopwords_set = set(stopwords.words(language))
       words_set = set (words)
       common_elements = words_set.intersection(stopwords_set)

   langratios[language] = len(common_elements)

   return langratios

def max_ratio(text):

  ratios = compute_ratios(text)

  mostLang = max(ratios , key=ratios.get)
  return mostLang

def main():

  text = "This is cool"
  x = max_ratio(text)
  print(x)

【问题讨论】:

  • 我们可能需要查看您的其余代码才能确定问题。
  • 你真的打电话 main吗?
  • 只是一个一般的故障排除思路,尝试在 main 开头输入:import pdb;pdb.set_trace()。单步执行代码以查看是否有任何感兴趣的内容出现。您可以使用next 和一行函数,同时使用 pdb 检查正在传递的变量发生了什么。 help 在 pdb 中查看其他命令。

标签: python language-detection


【解决方案1】:

与其他一些语言不同,main() 就像 Python 中的任何其他函数一样。如果你想让它运行,你必须显式调用它:

def main():
  ...

main()

【讨论】:

  • 谢谢。我没有明确地调用 main
  • 在以下条件 if __name__ == '__main__': 中调用 main() 的 pythonic 稍微多一点,这使得当你运行包含它的 python 文件时,main 将运行。但是,如果您将该模块导入其他地方,则 main 将不会运行。对于您的用例可能不是必需的,但绝对值得了解。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
相关资源
最近更新 更多