首页 > 解决方案 > 有没有办法通过多个参数拆分字符串而不是获取 TypeError: 'str' object cannot be mapped as an integer?

问题描述

有没有办法通过多个参数拆分字符串?当我按照下面的方式尝试时,我得到了

TypeError: 'str' object cannot be interpreted as an integer

调查一下,它应该可以工作。

该程序是一种新语言的翻译器,等等。男人是男性,所以男人de mno,而女性di felio而不是de felio。到目前为止,我已经完成了所有工作,我想开始重新安排句子顺序。我希望能够在每个dedi处分裂,而不仅仅是其中一个。我在网上查看并尝试使用我使用该re模块找到的解决方案,但最终没有奏效。

new_sentence = re.split(' de', ' di', translated_sentence)
print(new_sentence)

当我打印new_sentence时,如果我原来输入并且已经翻译the man is with the womande mno aili di felio. 我希望它像['de mno aili', 'di felio'].

我对拆分函数没有很好的理解,所以我的代码可能完全错误。

标签: pythonsplit

解决方案


您可以匹配空格,并使用字符类d[ei]将 de 或 di 与正则表达式匹配。如果不希望部分匹配,可以\b在末尾添加单词边界。

import re
translated_sentence = "The program is a translator to a new language, etc. man is masculine so the man is de mno while woman which is feminine would be di felio instead of de felio."

new_sentence = re.split(r' d[ei]\b', translated_sentence)

print(new_sentence)

输出

['The program is a translator to a new language, etc. man is masculine so the man is', ' mno while woman which is feminine would be', ' felio instead of', ' felio.']

查看Python 演示


推荐阅读