用python编写一个通过Unix列出相邻单词的脚本?

2024-04-16 20:40:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎样才能通过嵌套字典在python中编写一个脚本,它将txt文件写成

white,black,green,purple,lavendar:1

red,black,white,silver:3

black,white,magenta,scarlet:4

并将其打印到字符之前的每个条目,以及它旁边显示的所有邻居

^{pr2}$

等等

编辑:好吧,我没有发表我所拥有的,因为它是相当不真实的…我会更新它,如果我发现任何其他。。。我只是被困了一段时间- 我只想办法把每个单词/字母放在单独的一行上:

from sys import argv
script,filename=argv
txt=open(filename)
for line in txt:
    line=line[0:line.index(';')]
    for word in line.split(","):
        print word

我想我想要的是有某种for循环,遍历每个单词,如果这个单词不在原始词典中,我会将它添加到其中,然后在文件中搜索出现在它旁边的单词。在


Tags: 文件intxt脚本for字典linegreen
3条回答

输入

a,c,f,g,hi,lw:1

f,g,j,ew,f,h,a,w:3

fd,s,f,g,s:4

编码

^{pr2}$

输出

{'a': ['c', 'h', 'w'],
'c': ['a', 'f'],
'ew': ['j', 'f'],
'f': ['c', 'g', 'g', 'ew', 'h', 's', 'g'],
'fd': ['s'],
'g': ['f', 'hi', 'f', 'j', 'f', 's'],
'h': ['f', 'a'],
'hi': ['g', 'lw'],
'j': ['g', 'ew'],
'lw': ['hi'],
's': ['fd', 'f', 'g'],
'w': ['a']}

整理预先打印好的词典是留给读者的一项练习。(因为字典本质上不按任何顺序排序,删除重复项而不改变列表的顺序也很烦人)。在

简单解决方案:

for word, neighbour_list in neighbours.items():
    print word, ':', ', '.join(set(neighbour_list))

但这确实改变了顺序。在

给你:

from collections import defaultdict

char_map = defaultdict(set)
with open('input', 'r') as input_file:
    for line in input_file:
        a_list, _ = line.split(':') # Discard the stuff after the :
        chars = a_list.split(',') # Get the elements before : as a list
        prev_char = ""
        for char, next_char in zip(chars, chars[1:]): # For every character add the 
                                                      # next and previous chars to the 
                                                      # dictionary
            char_map[char].add(next_char)
            if prev_char:
                char_map[char].add(prev_char)
            prev_char = char

print char_map
def parse (input_file):
char_neighbours = {}
File = open(input_file,'rb')
for line in File:
    line = line.strip().split(':')[0]
    if line != "":
        csv_list=line.split(',')
        for i in xrange(0,len(csv_list)-1):
            value = char_neighbours.get(csv_list[i]) or False
            if value is False:
                char_neighbours[csv_list[i]] = []
            if(i<len(csv_list)):
                if str(csv_list[i+1]) not in char_neighbours[str(csv_list[i])]:
                    char_neighbours[str(csv_list[i])].append(str(csv_list[i+1]))
            if(i>0):
                if str(csv_list[i-1]) not in char_neighbours[str(csv_list[i])]:
                    char_neighbours[str(csv_list[i])].append(str(csv_list[i-1]))
return char_neighbours

if __name__ == "__main__":
    dictionary=parse('test.txt')
    print dictionary

parse方法返回一个字符串字典,其中有一个邻居列表作为它们的值

相关问题 更多 >