Python中嵌入了c。调用PyRun_SimpleString是否同步?

时间:2012-10-24 19:27:59

标签: c++ python translation embedding

人。 如果你能帮助我,我将不胜感激。 该应用程序的目的是将句子中出现的词汇从俄语翻译成英语。我是在sdict格式词汇表的帮助下完成的,这是由c ++程序调用的python脚本查询的。

我的目的是获得以下输出:

  

Выставка/ exhibition ::1конгресс/ congress ::2организаторами/ organizer ::3которой/ which ::4являются/ appear ::5РАО/ NONE ::6ЕЭС/ NONE ::7России/ NONE :: 8 EESR / ::9нефтяная/ oil ::10компания/ company ::11ЮКОС/ NONE :: 12 YUKOS / NONE ::13и/ and ::14администрация/ administration :: 15 Томской/ NONE ::16области/ region ::17продлится/ last ::18четыре/ four ::19дня/ day :: 20

以下代码成功完成了句子,但是对于第二句等等,我得到了错误的输出:

  

Егор/ NONE ::1Гайдар/ NONE ::2возглавлял/ NONE ::3первое/ head ::4российское/ first ::5правительство/ NONE ::6которое/ government: :7называли/ which ::8правительством/ call ::9камикадзе/ government :: 10

注意: NONE用于缺少翻译的字词。

我正在运行以下C ++代码摘录,实际上调用了PyRun_SimpleString

for (unsigned int i = 0; i < theSentenceRows->size(); i++){

  stringstream ss;
  ss << (i + 1);
  parsedFormattedOutput << theSentenceRows->at(i)[FORMINDEX] << "/";
  getline(lemmaOutFileForTranslation, lemma);

  PyObject *main_module, *main_dict;
  PyObject *toTranslate_obj, *translation, *emptyString;
  /* Setup the __main__ module for us to use */
  main_module = PyImport_ImportModule("__main__");
  main_dict   = PyModule_GetDict(main_module);

  /* Inject a variable into __main__, in this case toTranslate */
  toTranslate_obj = PyString_FromString(lemma.c_str());
  PyDict_SetItemString(main_dict, "start_word", toTranslate_obj);

  /* Run the code snippet above in the current environment */
  PyRun_SimpleString(pycode);
  **usleep(2);**
  translation = PyDict_GetItemString(main_dict, "translation");
  Py_XDECREF(toTranslate_obj);

  /* writing results */
  parsedFormattedOutput << PyString_AsString(translation) << "::" << ss.str() << " ";

其中pycode定义为:

const char *pycode =
    "import sys\n"
    "import re\n"
    "import sdictviewer.formats.dct.sdict as sdict\n"
    "import sdictviewer.dictutil\n"
    "dictionary = sdict.SDictionary( 'rus_eng_full2.dct' )\n"
    "dictionary.load()\n"
    "translation = \"*NONE*\"\n"
    "p = re.compile('( )([a-z]+)(.*?)( )')\n"
    "for item in dictionary.get_word_list_iter(start_word):\n"
    "        try:\n"
    "            if start_word == str(item):\n"
    "                instance, definition = item.read_articles()[0]\n"
    "                translation = p.findall(definition)[0][1]\n"
    "        except:\n"
    "            continue\n";

我注意到第二句输出有些延迟,所以我添加了usleep(2);到C ++时认为它发生是因为调用PyRun_SimpleString不是同步的。然而,它没有帮助,我不确定这是什么原因。对于跟随和增加的句子,会出现延迟错误。

那么,对PyRun_SimpleString的调用是否同步?也许,在C ++和Python之间共享变量值是不对的? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

根据the docs,它是同步的。

我建议你单独从C ++代码中测试python代码,这样可以更容易地调试它。这样做的一种方法是将代码粘贴到交互式解释器中并逐行执行。在调试时,我会将Winston Ewert的评论放在第二位。