これは少し宿題ではないですか :) もしそうなら、大騒ぎしても大丈夫です。あまり詳しく説明するのではなく、実行しようとしているタスクについて考えてください。
各行について:
- それを読んで
- 単語に分割します(空白 - .split() )
- 中間の単語を色に変換します (マッピングに基づく -> cf: python dict()
- 最初の単語、矢印、3 番目の単語、および色を出力します
NetworkX を使用したコード (networkx.lanl.gov/)
'''
plot relationships in a social network
'''
import networkx
## make a fake file 'ex.txt' in this directory
## then write fake relationships to it.
example_relationships = file('ex.txt','w')
print >> example_relationships, '''\
Jane Doe likes Fred
Chris dislikes Joe
Nate knows Jill \
'''
example_relationships.close()
rel_colors = {
'likes': 'blue',
'dislikes' : 'black',
'knows' : 'green',
}
def split_on_verb(sentence):
''' we know the verb is the only lower cased word
>>> split_on_verb("Jane Doe likes Fred")
('Jane Does','Fred','likes')
'''
words = sentence.strip().split() # take off any outside whitespace, then split
# on whitespace
if not words:
return None # if there aren't any words, just return nothing
verbs = [x for x in words if x.islower()]
verb = verbs[0] # we want the '1st' one (python numbers from 0,1,2...)
verb_index = words.index(verb) # where is the verb?
subject = ' '.join(words[:verb_index])
obj = ' '.join(words[(verb_index+1):]) # 'object' is already used in python
return (subject, obj, verb)
def graph_from_relationships(fh,color_dict):
'''
fh: a filehandle, i.e., an opened file, from which we can read lines
and loop over
'''
G = networkx.DiGraph()
for line in fh:
if not line.strip(): continue # move on to the next line,
# if our line is empty-ish
(subj,obj,verb) = split_on_verb(line)
color = color_dict[verb]
# cf: python 'string templates', there are other solutions here
# this is the
print "'%s' -> '%s' [color='%s'];" % (subj,obj,color)
G.add_edge(subj,obj,color)
#
return G
G = graph_from_relationships(file('ex.txt'),rel_colors)
print G.edges()
# from here you can use the various networkx plotting tools on G, as you're inclined.