首页 文章

使用python中的字典在文本文件中查找字典单词

提问于
浏览
0

我读了how to check dictionary words我想到了用字典检查我的文本文件 . 我已经阅读了pyenchant指令,我想如果我使用 get_tokenizer 给我回复文本文件中的所有字典单词 .

所以这就是我被困住的地方:我希望我的程序以段落的形式给我所有字典词组 . 一旦遇到任何垃圾字符,就会认为段落中断,并忽略所有内容,直到找到X个连续的单词 .

我希望它以 filename_nnn.txt 的顺序读取文本文件,解析它,然后写入 parsed_filname_nnn.txt . 我没有去做任何文件操作 .

到目前为止我所拥有的:

import enchant
from enchant.tokenize import get_tokenizer, HTMLChunker
dictSentCheck = get_tokenizer("en_US")
sentCheck = raw_input("Check Sentense: ")

def check_dictionary():
    outcome = dictCheck.check(wordCheck) 
    test = [w[0] for w in dictSentCheck(sentCheck)]
      • 示范文本 - - -

英国板球与津巴布韦切断关系2008年6月25日星期三文字< void(0);>< void(0);> < void(0);>电子邮件< void(0);>打印EMAIL此文章您的姓名:您的电子邮件地址:收件人姓名:收件人的电子邮件地址:&lt ;;>添加另一位收件人您的评论:发送邮件&lt ;无效(0);>关闭此表格< http://ad.au.doubleclick.net/jump/sbs.com.au/worldnews; sz = 300x250; tile = 2; ord = 123456789?>英格兰和威尔士板球委员会(ECB)宣布暂停与津巴布韦的所有联系,并于明年取消津巴布韦的英格兰之旅 .

该脚本应返回:

英格兰板球队周三削减与津巴布韦的关系英格兰和威尔士板球委员会(ECB)宣布暂停与津巴布韦的所有联系并取消津巴布韦明年的英格兰之旅

我接受了abarnert的回应 . 以下是我的最终剧本 . 请注意,这是非常低效的,应该清理一些 . 同样免责声明我从很久以前就没有编码 .

import enchant
from enchant.tokenize import get_tokenizer
import os

def clean_files():
    os.chdir("TARGET_DIRECTORY")
    for files in os.listdir("."):
           #get the numbers out file names 
           file_number = files[files.rfind("_")+1:files.rfind(".")]

           #Print status to screen
           print "Working on file: ", files

           #Read and process original file
           original_file = open("name_"+file_number+".txt", "r+")
           read_original_file = original_file.read();

           #Start the parsing of the files
           token_words = tokenize_words(read_original_file)
           parse_result = ('\n'.join(split_on_angle_brackets(token_words,file_number)))
           original_file.close()

           #Commit changes to parsed file
           parsed_file = open("name_"+file_number+"_parse.txt", "wb")
           parsed_file.write(parse_result);
           parsed_file.close()

def tokenize_words(file_words):
    tokenized_sentences = get_tokenizer("en_US")
    word_tokens = tokenized_sentences(file_words)
    token_result = [w[0] for w in word_tokens]
    return token_result

def check_dictionary(dict_word):
    check_word = enchant.Dict("en_US")
    validated_word = check_word.check(dict_word)
    return validated_word

def split_on_angle_brackets(token_words, file_number):
    para = []
    bracket_stack = 0
    ignored_words_per_file = open("name_"+file_number+"_ignored_words.txt", "wb")
    for word in token_words:
        if bracket_stack:
            if word == 'gt':
                bracket_stack -= 1
            elif word == 'lt':
                bracket_stack += 1
        else:
            if word == 'lt':
                if len(para) >= 7:
                    yield ' '.join(para)
                para = []
                bracket_stack = 1
            elif word != 'amp':
                if check_dictionary(word) == True:
                    para.append(word)
                    #print "append ", word
                else:
                       print "Ignored word: ", word
                       ignored_words_per_file.write(word + " \n")
    if para:
        yield ' '.join(para)

    #Close opened files
    ignored_words_per_file.close()

clean_files()

1 回答

  • 0

    我仍然不确定你的问题究竟是什么,或者你的代码应该做什么 .

    但这条线似乎是关键:

    test = [w[0] for w in dictSentCheck(sentCheck)]
    

    这会为您提供所有单词的列表 . 它包括像 ltgt 这样的词 . 并且你想要删除 ltgt 对中的任何内容 .

    而且,正如您在评论中所说,“我可以将所需的连续单词数设置为7” .

    所以,像这样:

    def split_on_angle_brackets(words):
        para = []
        bracket_stack = 0
        for word in words:
            if bracket_stack:
                if word == 'gt':
                    bracket_stack -= 1
                elif word == 'lt':
                    bracket_stack += 1
            else:
                if word == 'lt':
                    if len(para) >= 7:
                        yield ' '.join(para)
                    para = []
                    bracket_stack = 1
                else:
                    para.append(word)
        if para:
            yield ' '.join(para)
    

    如果您将其与样本数据一起使用:

    print('\n'.join(split_on_angle_brackets(test)))
    

    你得到这个:

    English cricket cuts ties with Zimbabwe Wednesday June text
    print EMAIL THIS ARTICLE your name your email address recipient's name recipient's email address
    add another recipient your comment Send Mail
    The England and Wales Cricket Board ECB announced it was suspending all ties with Zimbabwe and was cancelling Zimbabwe's tour of England next year
    

    这与您的示例输出不匹配,但我想不出任何可以提供示例输出的规则,所以我试图实现您描述的规则 .

相关问题