亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從python中的單詞列表中查找最長的常用單詞序列

從python中的單詞列表中查找最長的常用單詞序列

慕斯王 2022-12-20 14:32:43
我搜索了很多解決方案,我確實發現了類似的問題。此答案返回可能不屬于輸入列表中所有字符串的最長字符序列。此答案返回必須屬于輸入列表中所有字符串的最長公共 WORDS 序列。我正在尋找上述解決方案的組合。也就是說,我想要可能不會出現在輸入列表的所有單詞/短語中的最長的常見單詞序列。以下是預期的一些示例:['exterior lighting', 'interior lighting']-->'lighting'['ambient lighting', 'ambient light']-->'ambient'['led turn signal lamp', 'turn signal lamp', 'signal and ambient lamp', 'turn signal light']-->'turn signal lamp'['ambient lighting', 'infrared light']-->''謝謝
查看完整描述

2 回答

?
SMILET

TA貢獻1796條經驗 獲得超4個贊

此代碼還將按列表中最常見的單詞對所需列表進行排序。它會計算列表中每個單詞的數量,然后剪切只出現一次的單詞并對其進行排序。


lst=['led turn signal lamp', 'turn signal lamp', 'signal and ambient lamp', 'turn signal light'] 

d = {}

d_words={}

for i in lst:

    for j in i.split():

      if j in d:

          d[j] = d[j]+1

      else:

          d[j]= 1

for k,v in d.items():

    if v!=1:

        d_words[k] = v

sorted_words = sorted(d_words,key= d_words.get,reverse = True)

print(sorted_words)


查看完整回答
反對 回復 2022-12-20
?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

一個相當粗略的解決方案,但我認為它有效:


from nltk.util import everygrams

import pandas as pd


def get_word_sequence(phrases):


    ngrams = []


    for phrase in phrases:        

        phrase_split = [ token for token in phrase.split()]

        ngrams.append(list(everygrams(phrase_split)))


    ngrams = [i for j in ngrams for i in j]  # unpack it    


    counts_per_ngram_series = pd.Series(ngrams).value_counts()


    counts_per_ngram_df = pd.DataFrame({'ngram':counts_per_ngram_series.index, 'count':counts_per_ngram_series.values})


    # discard the pandas Series

    del(counts_per_ngram_series)


    # filter out the ngrams that appear only once

    counts_per_ngram_df = counts_per_ngram_df[counts_per_ngram_df['count'] > 1]


    if not counts_per_ngram_df.empty:    

        # populate the ngramsize column

        counts_per_ngram_df['ngramsize'] = counts_per_ngram_df['ngram'].str.len()


        # sort by ngramsize, ngram_char_length and then by count

        counts_per_ngram_df.sort_values(['ngramsize', 'count'], inplace = True, ascending = [False, False])


        # get the top ngram

        top_ngram = " ".join(*counts_per_ngram_df.head(1).ngram.values)


        return top_ngram


    return ''


查看完整回答
反對 回復 2022-12-20
  • 2 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號