在Python中从txt文件中查找紧跟在两个输入字之后的字

2024-05-29 00:17:06 发布

您现在位置: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]) 

Tags: 文件txt字典aswithopen单词trees
2条回答

假设你的文件看起来像这样

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

像这样的?(应该很容易适应……)

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"], ...

相关问题 更多 >

    热门问题