[英]Finding a word following two input words from txt file in Python
我正在制作一个字典,其中键是 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])
像这样的东西? (应该很容易适应......)
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"], ...
假设你的文件看起来像这样
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.