예제 #1
0
def make_word_to_morpheme_list_dict(mecab, path):
    dic = {}
    with codecs.open(path, 'r', 'utf-8') as f:
        messages = json.loads(f.read())

        for message_dic in messages:
            message = message_dic['message']
            msec = message_dic['offsetMsec']

            # 正規化してからMeCabに渡す
            rows = mecab.parse(normalize_neologd(message))
            # 形態素が行ごとにあるのでそれで分割していく
            words = []
            for row in rows.split('\n'):
                cols = row.split('\t')
                if (len(cols) == 0 or cols[0] == 'EOS'):
                    continue
                word = cols[0]
                if word == '':
                    continue
                words.append(word)

                o = { 'words':words, 'original':message, 'msec': msec }
                if word in dic:
                    dic[word].append(o)
                else:
                    dic[word] = [o]

    return dic
예제 #2
0
def restore_chat(mecab, id, keywords):
    livechat_json_path = './livechat/{}.json'.format(id)
    morpheme_dic = restore_sentence.make_word_to_morpheme_list_dict(
        mecab, livechat_json_path)

    chats = []
    memo = set()
    count = 0
    for keyword in keywords:
        if keyword not in morpheme_dic:
            continue

        # キーワードを含むチャットについての情報
        # [{'msec': 0, 'original': '', 'words': ['', ...]}]
        objs = morpheme_dic[keyword]

        # キーワードから復元したチャット
        sentences = restore_sentence.restore_sentence(morpheme_dic, keyword)

        # 登録されたかどうかチェック用
        appended = False

        # 復元したチャットには時間の情報がないのでそこも復元する
        for sentence in sentences:
            # sentenceは単語ごとの配列になっているので結合して文字列にする
            sentence_str = ''.join(sentence)
            # mecabで'do it'のような単語をパースしたときに固有名詞扱いになって1単語になるものがある
            # チャットを探すときに都合が悪いのでスペースを削除する
            sentence_str_for_search = sentence_str.replace(' ', '')

            # sentence_strが完全に含まれているチャットを探す
            for obj in objs:
                # ノーマライズして空白を削除
                original_chat = normalize_neologd(obj['original']).replace(
                    ' ', '')
                if original_chat.find(sentence_str_for_search) >= 0:
                    # keywordによっては既に選ばれたsentence_strが候補になる可能性がある
                    # 例えば'二'というkeywordと'二重'というキーワードがあったとき、同じものが選ばれる可能性がある
                    # それと元々のチャットのなかにほぼ同じ内容があった場合、形態素解析の都合上かぶってしまうことがある
                    # '昨日は十五夜だったね' => ['昨日', 'は', '十', '五', '夜', 'だっ', 'た', 'ね', 'EOS', '']
                    # '十五夜だったね' => ['十五夜', 'だっ', 'た', 'ね', 'EOS', '']
                    # のように十五夜がバラバラにされた場合、別のsentenceとして表れてしまう
                    if not sentence_str in memo:
                        memo.add(sentence_str)
                        chats.append({
                            'msec': obj['msec'],
                            'sentence': sentence_str
                        })
                        appended = True
                    break

        if not appended:
            print('warning, not appended - {}'.format(keyword))

        # 500単語分登録する
        count = count + 1
        if count >= 500:
            break

    return chats
예제 #3
0
def get_keywords(mecab, path, accept_part=['名詞', '形容詞']):
    with codecs.open(path, encoding='utf-8') as f:
        messages = json.loads(f.read())
        keywords = []
        for message_dic in messages:
            if 'message' not in message_dic:
                print('{}:{}'.format(path,message_dic))
                continue
            message = message_dic['message']
            # 正規化してからMeCabに渡す
            rows = mecab.parse(normalize_neologd(message))
            # 形態素が行ごとにあるのでそれで分割していく
            for row in rows.split('\n'):
                cols = row.split('\t')
                if (len(cols) == 0):
                    continue

                word = cols[0]
                if check_accept(word, cols, accept_part):
                    keywords.append(word)
                
        return keywords
예제 #4
0
def normalize(sentences: list) -> list:
    from normalize_neologd import normalize_neologd
    return normalize_neologd(sentences)
예제 #5
0
 def __init__(self, text):
     self.text = nn.normalize_neologd(text)
     self.words = _getWords(self.text)
예제 #6
0
client = jubatus.Classifier(host, port, name)

conn = sqlite3.connect('../data/sqlite.db')
cur = conn.cursor()


while True:
    try:
        print '> ',
        target_url = sys.stdin.readline()
        target_html = requests.get(target_url).text

        root = lxml.html.fromstring(target_html)
        Genre1 = root.cssselect('li.nth-1')[0].text_content().strip()
        HeadLine = normalize_neologd(root.cssselect('.article article h1')[0].text_content())
        article = ''
        for i in root.cssselect('.article article p'):
            article += normalize_neologd(i.text_content())
            article += '\n'
        DateLine = root.cssselect('time')[0].text_content().replace(u'年', u'-').replace(u'月', u'-').replace(u'日', u'').replace(u'時', u':').replace(u'分', u':') + u'00'

        print u'Add Data'
        print Genre1
        print HeadLine
        print DateLine
        print article
        client.train([(Genre1, Datum({u'aricel':article, u'HeadLine':HeadLine}))])
        cur.execute(u"INSERT INTO item(Genre1, HeadLine, DateLine, article) VALUES('{0}', '{1}', '{2}', '{3}')".format(Genre1, HeadLine, DateLine, article))
        conn.commit()
    except requests.exceptions.MissingSchema:
def main(bing_key):
    
    """
    単語取得の出発点となるクエリを取得
    以下のURLは若者が使う新語・流行語一覧を記載している
    """
    query = []
    r = requests.get('http://bosesound.blog133.fc2.com/blog-entry-155.html')
    soup = BeautifulSoup(r.text, "html.parser")
    for li in soup.find_all('li'):
        query.append(li.string)


    """
    各クエリでの検索結果300件のタイトルとスニペットを取得
    """
    bing = Bing(bing_key)

    text_set = []
    for q in query:
        search_results = bing.web_search(q, 300, ["Title", "Description"])
        for doc in search_results:
            #正規化をして追加する
            text_set.append(normalize_neologd(doc["Title"]))
            text_set.append(normalize_neologd(doc["Description"]))



    """
    text_setを用いて登録単語候補を作成する
    単語候補のパターンは分割された単語を2つつなげたもの
    """
    registration_word_candidate_by_bigram = []
    for text in text_set:
        words = text2words(text)
        ngram = wordNgram(words, 2)
        registration_word_candidate_by_bigram.extend(ngram)



    """
    候補を評価 そのフレーズに名詞と形容詞が計2つ存在するなら登録
    """
    registration_word = []
    for candidate in registration_word_candidate_by_bigram:
        mt = MeCab.Tagger("-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd/")
        node = mt.parseToNode(candidate)

        #名詞形容詞の数を数える
        num_of_meanigful = 0
        while node:
            feature = node.feature.split(',')
            if feature[0] == "名詞" or feature[0] == "形容詞":
                num_of_meanigful += 1
            node = node.next

        if num_of_meanigful == 2:
            registration_word.append(candidate)

    #重複を削除
    registration_word = list(set(registration_word))



    """
    辞書に追加する単語の読みを作成する
    """
    data = []
    for word in registration_word:
        mt = MeCab.Tagger("-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd/")
        node = mt.parseToNode(word)    
        kana = ""
        while node:
            feature = node.feature.split(',')
            #読みがないものは採録しないので*で判別する
            if len(feature) >= 8:
                kana += feature[7]
            else:
                kana += "*"

            node = node.next
    
        #最初と最後のBOS/EOSに関するものを削除
        kana = kana[1:-1]

        if "*" not in kana:
            data.append([word, kana])


    """
    データ書込
    """
    with open('new_words.txt', 'w') as f:
        writer = csv.writer(f, lineterminator='\n')
        writer.writerows(data)

    return
예제 #8
0
import sys
import normalize_neologd as nneo
import re
for line in sys.stdin:
    line = line.replace("。", "。\n")
    line = re.sub(r'<[^\]]*>', '', line)
    print(nneo.normalize_neologd(line))
def normalize(str):
    return normalize_neologd(str)
import os
import sys
from normalize_neologd import normalize_neologd

infile = sys.argv[1]
print("Counting line number...")
num_lines = sum(1 for line in open(infile))

outfile = os.path.splitext(infile)[0].replace("_extracted",
                                              "_normalized") + ".txt"
with open(outfile, 'w') as fout, open(infile) as fin:
    for i, line in enumerate(fin):
        if i > 0 and i % 20000 == 0:
            print("{0:10} / {1:10} lines ({2:1.1f} percent) done".format(
                i, num_lines, 100.0 * i / num_lines))
            sys.stdout.flush()
        if line.startswith('<doc') or line.startswith('</doc'):
            fout.write(line)
        else:
            fout.write(normalize_neologd(line) + "\n")
예제 #11
0
def normalize(str):
    return normalize_neologd(str)