我正在创建一个字典,其中键是txt文件中两个连续单词的元组,每个键的值是直接在键后面找到的单词列表。例如,
>>> with open('alice.txt') as f:
... d = associated_words(f)
>>> d[('among', 'the')]
>>> ['people', 'party.', 'trees,', 'distant', 'leaves,', 'trees', 'branches,', 'bright']
我的代码到目前为止,但尚未完成。有人可以帮忙吗?
def associated_words(f):
from collections import defaultdict
d = defaultdict(list)
with open('alice.txt', 'r') as f:
lines = f.read().replace('\n', '')
a, b, c = [], [], []
lines.replace(",", "").replace(".", "")
lines = line.split(" ")
for (i, word) in enumerate(lines):
d['something to replace'].append(lines[i+2])
答案 0 :(得分:0)
from pathlib import Path
from collections import defaultdict
DATA_PATH = Path(__file__).parent / '../data/alice.txt'
def next_word(fh):
'''
a generator that returns the next word from the file; with special
characters removed; lower case.
'''
transtab = str.maketrans(',.`:;()?!—', ' ') # replace unwanted chars
for line in fh.readlines():
for word in line.translate(transtab).split():
yield word.lower()
def handle_triplet(dct, triplet):
'''
add a triplet to the dictionary dct
'''
dct[(triplet[0], triplet[1])].append(triplet[2])
dct = defaultdict(list) # dictionary that defaults to []
with DATA_PATH.open('r') as fh:
generator = next_word(fh)
triplet = (next(generator), next(generator), next(generator))
handle_triplet(dct, triplet)
for word in generator:
triplet = (triplet[1], triplet[2], word)
handle_triplet(dct, triplet)
print(dct)
输出(摘录......;不在整个文本上运行)
defaultdict(<class 'list'>, {
('enough', 'under'): ['her'], ('rattle', 'of'): ['the'],
('suppose', 'they'): ['are'], ('flung', 'down'): ['his'],
('make', 'with'): ['the'], ('ring', 'and'): ['begged'],
('taken', 'his'): ['watch'], ('could', 'show'): ['you'],
('said', 'tossing'): ['his'], ('a', 'bottle'): ['marked', 'they'],
('dead', 'silence'): ['instantly', 'alice', "'it's"], ...
答案 1 :(得分:0)
假设您的文件看起来像这样
each them theirs tree life what not hope
代码:
lines = [line.strip().split(' ') for line in open('test.txt')]
d = {}
for each in lines:
d[(each[0],each[1])] = each[2:]
print d