Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.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_List_Spacy - Fatal编程技术网

Python 我如何修改一个";如果条件是“;为了同时将其应用于不同的列表?

Python 我如何修改一个";如果条件是“;为了同时将其应用于不同的列表?,python,list,spacy,Python,List,Spacy,我写了一个脚本来提取包含特定模式的大量句子。问题在于,对于某些模式,我检查了模式开头或结尾的属性值,以查看单词是否出现在特定列表中。我有4本字典,其中有两个肯定词和否定词的列表。到目前为止,我编写了脚本,我能够使用我用一本字典编写的函数。我在考虑如何改进my函数,以便在不重复字典中循环的bloc的情况下,同时使用4个字典 我给出了一个有两个字典的例子(因为脚本很长,所以我用所有必要的元素做了一个小例子) import spacy.attrs from spacy.attrs import POS

我写了一个脚本来提取包含特定模式的大量句子。问题在于,对于某些模式,我检查了模式开头或结尾的属性值,以查看单词是否出现在特定列表中。我有4本字典,其中有两个肯定词和否定词的列表。到目前为止,我编写了脚本,我能够使用我用一本字典编写的函数。我在考虑如何改进my函数,以便在不重复字典中循环的bloc的情况下,同时使用4个字典

我给出了一个有两个字典的例子(因为脚本很长,所以我用所有必要的元素做了一个小例子)

import spacy.attrs
from spacy.attrs import POS
import spacy
from spacy import displacy
from spacy.lang.fr import French
from spacy.tokenizer import Tokenizer
from spacy.util import compile_prefix_regex, compile_infix_regex, compile_suffix_regex
from spacy.lemmatizer import Lemmatizer
nlp = spacy.load("fr_core_news_md")
from spacy.matcher import Matcher#LIST 


##################### List of lexicon

# Lexique Diko
lexicon = open(os.path.join('/h/Ressources/Diko.txt'), 'r', encoding='utf-8')
data = pd.read_csv(lexicon, sep=";", header=None)
data.columns = ["id", "terme", "pol"]
pol_diko_pos = data.loc[data.pol =='positive', 'terme']
liste_pos_D = list(pol_diko_pos)
print(liste_pos[1])
pol_diko_neg = data.loc[data.pol =='negative', 'terme']
liste_neg_D = list(pol_diko_neg)
#print(type(liste_neg))


# Lexique Polarimots
lexicon_p = open(os.path.join('/h/Ressources/polarimots.txt'), 'r', encoding='utf-8')
data_p = pd.read_csv(lexicon_p, sep="\t", header=None)
#data.columns = ["terme", "pol", "pos", "degre"]
data_p.columns = ["ind", "terme", "cat", "pol", "fiabilité"]
pol_polarimot_pos = data_p.loc[data_p.pol =='POS', 'terme']
liste_pos_P = list(pol_polarimot_pos)
print(liste_pos_P[1])
pol_polarimot_neg = data_p.loc[data_p.pol =='NEG', 'terme']
liste_neg_P = list(pol_polarimot_neg)
#print(type(liste_neg))


# #############################     Lists 

sentence_not_extract_lexique_1 =[] #List of all sentences without the specified pattern
sentence_extract_lexique_1 = [] #list of sentences which the pattern[0] is present in the first lexicon

sentence_not_extract_lexique_2 =[] #List of all sentences without the specified pattern
sentence_extract_lexique_2 = [] #list of sentences which the pattern[0] is present in the second lexicon

list_token_pos = [] #list of the token found in the lexique
list_token_neg = [] #list of the token found in the lexique
list_token_not_found = [] #list of the token not found in the lexique

#PATTERN 

pattern1 = [{"POS": {"IN": ["VERB", "AUX","ADV","NOUN","ADJ"]}}, {"IS_PUNCT": True, "OP": "*"}, {"LOWER": "mais"} ] 

pattern1_tup = (pattern1, 1, True)

pattern3 = [{"LOWER": {"IN": ["très","trop"]}},
           {"POS": {"IN": ["ADV","ADJ"]}}]

pattern3_tup = (pattern3, 0, True)

pattern4 = [{"POS": "ADV"},  # adverbe de négation
            {"POS": "PRON","OP": "*"},
            {"POS": {"IN": ["VERB", "AUX"]}}, 
            {"TEXT": {"IN": ["pas", "plus", "aucun", "aucunement", "point", "jamais", "nullement", "rien"]}},]

pattern4_tup = (pattern4, None, False)

#Tuple of pattern

pattern_list_tup =[pattern1_tup, pattern3_tup, pattern4_tup]
pattern_name = ['first', 'second', 'third', 'fourth']
length_of_list = len(pattern_list_tup)
print('length', length_of_list)

#index of the value of attribute to check in the lexicon

value_of_attribute = [0,-1,-1]

# List of lexicon to use 

lexique_1 = [lexique_neg, lexique_pos]
lexique_2 = [lexique_2neg, lexique_2pos]


# text (example of some sentences)

file =b= ["Le film est superbe mais cette édition DVD est nulle !",
    "J'allais dire déplorable, mais je serais peut-être un peu trop extrême.",
    "Hélas, l'impression de violence, bien que très bien rendue, ne sauve pas cette histoire gothique moderne de la sécheresse scénaristique, le tout couvert d'un adultère dont le propos semble être gratuit, classique mais intéressant...",
    "Tout ça ne me donne pas envie d'utiliser un pieu mais plutôt d'aller au pieu (suis-je drôle).",
"Oui biensur, il y a la superbe introduction des parapluies au debut, et puis lorsqu il sent des culs tout neufs et qu il s extase, j ai envie de faire la meme chose apres sur celui de ma voisine de palier (ma voisine de palier elle a un gros cul, mais j admets que je voudrais bien lui foute mon tarin), mais c est tout, apres c est un film tres noir, lent et qui te plonge dans le depression.",
"Et bien hélas ce DVD ne m'a pas appris grand chose par rapport à la doc des agences de voyages et la petite dame qui fait ses dessins est bien gentille mais tout tourne un peu trop autour d'elle.",
"Au final on passe de l'un a l'autre sans subtilité, et on n'arrive qu'à une caricature de plus : si Kechiche avait comme but initial déclaré de fustiger les préjugés, c'est le contraire qui ressort de ce ''film'' truffé de clichés très préjudiciables pour les quelques habitants de banlieue qui ne se reconnaîtront pas dans cette lourde farce.",
"-ci écorche les mots, les notes... mais surtout nos oreilles !"]



# Loop to check each sentence and extract the sentences with the specified pattern from above

for pat in range(0, length_of_list):
    matcher = Matcher(nlp.vocab)  
    matcher.add("matching_2", None, pattern_list_tup[pat][0])
    # print(pat)
    # print(pattern_list_tup[pat][0])
    for sent in file:
        doc =nlp(sent)
        matches= matcher(doc)
        for match_id, start, end in matches:    
                    span = doc[start:end].lemma_.split()
                    #print(f"{pattern_name[pat]} pattern found: {span}") 

                   
这是我想修改的部分,以便将其用于另一个词典,目标是能够检索由4个不同词典提取的句子进行比较,然后检查两个以上的列表中存在哪些句子

 # Condition to use the lexicon and extract the sentence
                    
                    if (pattern_list_tup[pat][2]):
                        if (span[value_of_attribute[pat]] in lexique_1[pattern_list_tup[pat][1]]):
                            if sent not in sentence_extract:
                                sentence_extract_lexique_1.append(sent)
                            if (pattern_list_tup[pat][1] == 1):
                                list_token_pos.append(span[value_of_attribute[pat]])
                            if (pattern_list_tup[pat][1] == 0):
                                list_token_neg.append(span[value_of_attribute[pat]])
                        else:
                            list_token_not_found.append(span[value_of_attribute[pat]])  # the text form is not present in the lexicon need the lemma form
                            sentence_not_extract_lexique_1.append(sent)
                    else:
                        if sent not in sentence_extract:
                            sentence_extract_lexique_1.append(sent)
                    
print(len(sentence_extract))
print(sentence_extract)


我找到的一个解决方案是复制代码库,并更改存储句子的列表的名称,但由于我有两个字典,复制会使代码变长,有没有办法将两个字典(实际上是原来的4个字典)的循环组合起来然后将结果附加到好的列表中。例如,当我使用lexique_1时,所有提取的句子都会发送到“句子提取_lexique_1”以此类推。

在我看来,尝试使用if-elif-else链。if-not尝试仅使用if-elif块,因为elif语句捕捉到了特定的感兴趣条件。在这种情况下,您试图捕捉特定的条件,以便与句子进行比较和检查。请记住,如果尝试if-elif-else链,这是一个很好的方法ethod,但它只在你需要通过一个测试时才起作用。因为Python发现一个测试要通过,它跳过了其余的测试。它非常有效,允许你测试一个特定的条件。

问题是什么?@wwii请解释你自己,因为我不明白。这是一个问答网站。你的问题是什么,你是在要求别人重构你的测试吗您的代码?请阅读。注意:我不知道
spacy
,也不精通nlp,所以可能我有点困惑。