4

私は次の文字列を持っています:

>>>sentence='No, I shouldn't be glad, YOU should be glad.'

そして、私が欲しいのは、文の単語をキーとして、次の単語を値として辞書を作成することです。

>>>dict(sentence)
{('No,'): ['I'], ('I'): ['shouldn't'], ('shouldn't'): ['be'], ('be'): ['glad,', 'glad.'], ('glad,'): ['YOU'], ('YOU'): ['should'], ('should'): ['be']} 
                                                                 ^        ^       ^             
                                                                 |        |       |

単語が1つの文に複数回出現するかどうかを確認できるように、複数の値を取得します。それが最後の単語である場合、それは辞書に追加されません。単語が「、」または「。」で終わるため、「glad」は複数の値を取得しません。これは別の文字列になります。

4

5 に答える 5

4
import collections

sentence = "No, I shouldn't be glad, YOU should be glad."

d = collections.defaultdict(list)
words = sentence.split()
for k, v in zip(words[:-1], words[1:]):
   d[k].append(v)
print(d)

これにより、

defaultdict(<type 'list'>, {'No,': ['I'], 'be': ['glad,', 'glad.'], 'glad,': ['YOU'], 'I': ["shouldn't"], 'should': ['be'], "shouldn't": ['be'], 'YOU': ['should']})
于 2012-12-10T18:11:58.293 に答える
3

使用dict.setdefault()

In [9]: strs = "No, I shouldn't be glad, YOU should be glad."


In [19]: dic = {}

In [20]: for x, y in zip(words, words[1:]):
      dic.setdefault(x, []).append(y)     
   ....:     

In [21]: dic
Out[21]: 
{'I': ["shouldn't"],
 'No,': ['I'],
 'YOU': ['should'],
 'be': ['glad,', 'glad.'],
 'glad,': ['YOU'],
 'should': ['be'],
 "shouldn't": ['be']}
于 2012-12-10T18:15:58.473 に答える
0

これはテストされていませんが、近いはずです。

words = sentence.split()
sentenceDict = {}
for index in xrange(len(words)-1):
    if words[index] in sentenceDict:
        sentenceDict[words[index].append(words[index+1])
    else
        sentenceDict[words[index]] = [words[index+1]]
于 2012-12-10T18:14:13.213 に答える
0

順序が重要でない場合は、別の方法で

sentence="No, I shouldn't be glad, YOU should be glad."
#Split the string into words
sentence = sentence.split()
#Create pairs of consecutive words
sentence = zip(sentence,sentence[1:])
from itertools import groupby
from operator import itemgetter
#group the sorted pairs based on the key
sentence = groupby(sorted(sentence, key = itemgetter(0)), key = itemgetter(0))
#finally create a dictionary of the groups
{k:[v for _,v in  g] for k, g in sentence}
{'No,': ['I'], 'be': ['glad,', 'glad.'], 'glad,': ['YOU'], 'I': ["shouldn't"], 'should': ['be'], "shouldn't": ['be'], 'YOU': ['should']}
于 2012-12-10T18:31:33.007 に答える
0
import collections

sentence = "No, I shouldn't be glad, YOU should be glad."

d = collections.defaultdict(list)
words = sentence.split()
for k, v in zip(words[:-1], words[1:]):
   d[k].append(v)
print(d)

これにより、

defaultdict(<type 'list'>, {'No,': ['I'], 'be': ['glad,', 'glad.'], 'glad,': ['YOU'], 'I': ["shouldn't"], 'should': ['be'], "shouldn't": ['be'], 'YOU': ['should']})

@NLS:これに何かを追加したかっただけです。"d = collections.defaultdict(list)"のように、dictオブジェクトは単語の順序を保持しないため、文の順序を保持する必要がある場合は、タプルを使用する必要があります。

于 2012-12-10T18:37:23.613 に答える