2015-12-22 91 views
0

因此,我有一個非常長的帶有單詞的字符串,位於「$」符號和詞性之間。例如: 「$ dog -v。一種經常作爲寵物擁有的動物」如何根據字符串的字符將字符串分割爲塊

我想要做的是拉出「$」後面的每個單詞,並在「v」之前。並根據他們的言辭在字典中排序。在上面的例子中,輸出應該是{「dog」:「 - v。」}。通過這種方式,我將會得到一個字典,其中的鍵字是「-v」。表示它們是動詞。

我認爲這樣做將與字符串的切片和循環最好的方式,但我有最好的是這樣的:

my_dict = {} 
for i in words: 
    if i == "$": 
     for j in words[i:]: 
      if (j == "-") and (words[j:1] == "v") and (words[j:2] == "."): 
       my_dict.append(words[i:j]) 
       break 

,但上面的代碼中有這麼多的錯誤,我寧願人們不要把它們指出來,然後告訴我正確的方法。感謝您的幫助。

+0

我不明白。你首先說輸出應該是'{「dog」:「 - v。「}'('-v'作爲值和單詞作爲關鍵字),然後你說你最終會得到一個'dict',其中的鍵是'-v'? – RafaelC

+0

它總是會變成'-v '或者它可能會成爲' - 別的東西'? –

回答

0

如果我理解你的問題是正確的,你只能選擇「-v」。這意味着字典是沒有必要的。此外,字典必須有唯一的鍵,所以你可能不想使用這個 - 因爲動物可能會出現好幾次。字典的典型用法是將動物名稱作爲關鍵字,將出現的數量作爲值。 你也在嘗試切分一個角色。當你說for i in words我會成爲角色。 j也一樣。

這是一個列表,而不是一本字典你的代碼的工作示例:

my_dict = [] 

for i in range(len(words)): 
    if words[i]=="$": 
     for j in range(len(words[i:])): 
      if words[j] == "-" and words[j+1] == "v" and words[j+2] == ".": 
       my_dict.append(words[i:j]) 
       break 

print my_dict 
0

如果-v永遠是-v,您可以使用regular expressions這樣的:

import re 
s = "$dog -v. an animal that is often owned as a pet" 
word = re.findall(r'\$(.* -v)', s) 
d = {} 
lst = word[0].split() 
d[lst[0]] = lst[1] 
print (d) 

輸出:

{'dog': '-v'} 
0

不太確定y我們的預期產出。

我假設你會有其他的詞性標籤,如-n。另外,由於您在最終詞典中不清楚,我已經制作了兩個變體,您可以選擇適合您要求的變體。

你可以試試這個:

import re 

sentence = ''' 
$dog -v. an animal that is often owned as a pet 
$man -n. he is a man 
$jump -v. he jumped blah blah 
''' 

animals = re.findall(r'\$(.*)(?=\.)', sentence) #capture from $ to '.' 

posDict = {}   #dict stores POS tags as keys.. eg '-v':['dog','jump'] 
animalDict = {}  #dict stores animals as keys .. eg 'dog':['-v'] 

for item in animals: 
    word, pos = item.split() 

    if posDict.get(pos,'') == '' : 
     posDict[pos] = [] 

    if animalDict.get(word,'') == '' : 
     animalDict[word] = [] 

    posDict[pos].append(word) 
    animalDict[word].append(pos) 

輸出:

所以posDict現在擁有POS標籤(動詞,名詞等)作爲鍵。

>>> posDict 
{'-v': ['dog', 'jump'], '-n': ['man']} 

檢索如下所有動詞:

>>> posDict['-v'] 
['dog', 'jump'] 

如果在另一方面,你想要的動物和它們的相關標籤:

>>> animalDict 
{'man': ['-n'], 'dog': ['-v'], 'jump': ['-v']} 
>>> animalDict['dog'] 
['-v'] 

使用其以往任何時候都適合您的要求的字典。不要同時使用!