Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python从单词列表中删除不需要的字符并将其清除到另一个列表中?_Python_Regex_List_Search - Fatal编程技术网

如何使用Python从单词列表中删除不需要的字符并将其清除到另一个列表中?

如何使用Python从单词列表中删除不需要的字符并将其清除到另一个列表中?,python,regex,list,search,Python,Regex,List,Search,我是Python新手,正在处理词典数据库。 我有三个列表:第一个包含我要测试的数据库中的几个单词,第二个包含前缀,第三个包含后缀。 我需要制作另一个名为部首的列表,其中包含第一个列表中与其他两个列表匹配但前缀或后缀已删除的单词 我确信我在这里没有使用正确的方法,但以下是我的代码: #coding UTF-8 import re from re import search words = ["flore", "fleur", "fleuriste", "remaniement", "rem

我是Python新手,正在处理词典数据库。 我有三个列表:第一个包含我要测试的数据库中的几个单词,第二个包含前缀,第三个包含后缀。 我需要制作另一个名为部首的列表,其中包含第一个列表中与其他两个列表匹配但前缀或后缀已删除的单词

我确信我在这里没有使用正确的方法,但以下是我的代码:

#coding UTF-8
import re 
from re import search 


words = ["flore", "fleur", "fleuriste", "remaniement", "remanier", "manier", "maniable", "désaimer", "aimer", "aimant", "mêler", "emmêler", "désemmêler"]
radicals = []
i = 0
motifp = "^[re|em|dés]"
motifs = "[iste|ment|er|ant]$"

while i < len(words) : 
    if re.search(motifs, words[i]) : 
        del(motifp, words[i])
        del(motifs, words[i])
        radicals.append(words[i])
    i = i + 1
print(radicals)
它返回以下错误:

['fleur']
Traceback (most recent call last):
  File "C:\Users\alice\OneDrive\Documents\Visual Studio 2017\Projects\PythonApplication4\PythonApplication4\PythonApplication4.py", line 14, in <module>
    del(motifp, words[i])
NameError: name 'motifp' is not defined
Press any key to continue . . .
我真的需要你的帮助。。。
非常感谢

您想要的是迭代每个单词并删除任何已定义的前缀或后缀。就这样。由于某些部首是相同的,例如,对于fleur和Fleurite,使用一组


你的后缀和前缀是否总是位于单词的开头和结尾。。。是否要从单词数组中删除?因为现在它删除了整个Motif和Motif p变量,这就是崩溃的原因。是的,前缀总是在单词的开头,后缀总是在单词的结尾。@Farboindriven我实际上没有,del可能是一个糟糕的解决方案,因为我基本上只想忽略单词列表中的前缀和后缀,并将所有至少包含一个单词的单词放在没有前缀或后缀的部首列表中。。。如果可能的话,我会这样做:words[I]=words[I]-motipyyour regex是错误的,[re | em | dés]表示来自r,e,|,m,d,é,s的单个字符。你可能是说re | em | dés还是?:re | em | dés]非常感谢,它工作得非常好!虽然如果我想保留fleur和Fleurite的部首,即使它们是相同的,我该怎么办?@Alicephenix在这种情况下,部首应该是一个列表,你只需要做部首。appendword。好的,非常感谢,只是用一个列表测试了一下,很完美!
import re 

words = ["flore", "fleur", "fleuriste", "remaniement", "remanier", "manier", "maniable", "désaimer", "aimer", "aimant", "mêler", "emmêler", "désemmêler"]
radicals = set()
motifp = "^(re|em|dés)"
motifs = "(iste|ment|er|ant)$"

for word in words:
    word = re.sub(motifp, '', word)
    word = re.sub(motifs, '', word)
    radicals.add(word)
print(radicals)