簡體   English   中英

將Dict中的鍵與字符串匹配

[英]Match Key in a Dict to a String

你好漂亮的人!

dict = {'Awesome' : 'Sauce', 'Foo' : 'Barr'}

Col A Col B
1     'This is Awesome'
2     'I really foo him' 

我正在嘗試找到迭代數據集/幀的最pythonic方法,並返回任何字符串匹配dict的值。

因此,對於數字1,我​​想在列c中返回Sauce,並在相應的行中返回2'barr',但是在col c中。

如果這很重要,我正在處理csv / excel文件。

任何幫助,將不勝感激。 我很高興使用Pandas和NP庫。

溫編輯:

ID     Name of Course
0      Super Event Training: English Event...
1      Start with our Maths Training...
2      Live online Biology Training...
3      Maths throughout time...
4      Online Q&A Webinar: History..
5      Start with our Creative ...
6      Spring Conf with Author
7      Physics in our age ...
8      Spring Conf
9      Start with our educational items...
10     Education delivery in India...
11     English IELTS, Access to University..
12     Our Core Products for Empowerment..

我有一個DF這樣的大約500行,我正在借助API來抓取,我需要將這個自由格式文本轉換為我的字典中的值。 我所做的是確定了我已經放入我的鍵值並分配給dict值的關鍵詞,因此我們可以分析數據。

也許使用dict不是最好的方法嗎? 任何建議將不勝感激。

DN。

你只能使用python

[''.join(z) for z in [[y[1] if y[0] in x  else '' for x in df['Col B'] ] for y in d.items()]]
Out[22]: ['Sauce', 'Barr']

因此,如果您可以逐行讀取csv(或將其拆分到可以訪問b列中值的位置),下面將為您提供列B中與字典中的鍵匹配的句子中所有值的列表。

word_dict = {'Awesome' : 'Sauce', 'Foo' : 'Barr'}
s1 = 'This is Awesome'
matches = [x for x in s1.split() if x in dict.keys()]
>> matches = ['Awesome']

它的工作原理是使用string.split()將句子分成單詞。 然后列表推導迭代生成的單詞列表並檢查它是否是字典中的鍵,如果它是鍵,則將其添加到新列表中,如果不是鍵,則將其忽略。

像這樣的東西?

def get_col3(text,d):
    ret = ""
    keys = list(d.keys())
    vals = list(d.values())
    for key in keys:
        if key.lower() in text.lower():
            idx = keys.index(key)
            ret+=vals[idx]+" "
    return ret

d = {'Awesome' : 'Sauce', 'Foo' : 'Barr'}

text1 = 'This is Awesome'
text2 =  'I really foo him'
text3 =  'That was Awesome foo to him'

print(get_col3(text3,d))

如果要顯式迭代字典和Dataframe,可以使用:

mapper = {'Awesome' : 'Sauce', 'Foo' : 'Barr'}

data = {"Col B": ["This is Awesome", "I really foo him"]}

df = pd.DataFrame(data)

for item in mapper:
    for i in range(len(df)):
        if item.lower() in df["Col B"].iloc[i].lower():
            print(mapper[item])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM