2017-05-03 4 views
1

私はテキストのコレクションを持っています。それらのテキストのそれぞれは正規化され、リストにトークン化されます - 私は以下のコードを投稿します - 私が持っているものはリストのリストです。それぞれはテキストです。私がしたいのは、各単語のすべての場所をテキストで取得することです。Python:リストのインデックスのパーセンテージを長さで割ったアイテム配置を取得

例:「ここはテキストですが、長いテキストではありません。

here: 1  (Not counting pythonically here.) 
is: 2, 6 
a: 3, 8 
text: 4, 10 
it: 5 
not: 7 
long: 9 

これらの位置は、しかし、比較することはできませんので、私は、テキストの長さによってそれらを分割することによって、それらを正常化したいと思います:

here: 0.1 
is: 0.2, 0.6 

私の目標は、収集できるようにするには、その後ですすべてこのような単語の集合をテキスト集合全体に渡って配置し、場所の平均を取って、テキストの特定の部分にいくつかの単語が規則的に出現しているかどうかを調べる。これは、David Robinson has done in Rです。私はPythonでこれを実行しようとしています:私はつまずくところ

# =-=-=-=-=-=-=-=-=-=-= 
# Data Load & Tokenize 
# =-=-=-=-=-=-=-=-=-=-= 

import pandas 
import re 
from nltk.tokenize import WhitespaceTokenizer 

# LOAD 
colnames = ['author', 'title', 'date' , 'length', 'text'] 
df = pandas.read_csv('../data/talks_3.csv', names=colnames) 
talks = df.text.tolist() 
authors = df.author.tolist() 
dates = df.date.tolist() 
years = [re.sub('[A-Za-z ]', '', item) for item in dates] 
authordate = [author+" "+year for author, year in zip(authors, years)] 

# TOKENIZE 
tokenizer = WhitespaceTokenizer() 
texts = [] 
for talk in talks: 
    raw = re.sub(r"[^\w\d'\s]+",'', talk).lower() 
    tokens = tokenizer.tokenize(raw) 
    texts.append(tokens) 

そしてここにはある - それは擬似コードをするためにかなり迅速に動作するコードから行く:

def get_word_placement(listname): 
    wordplaces = {} 
    for word in listname: 
     get the word 
     get its location of listname[word]/len(listname) 
     attach those locations to word 

答えて

1

あなた場合enumerateリストを、その後、あなたは、インデックスを持っている、との相対位置を取得するために長さで割ることができます。

コード:

word_list = 'Here is a text it is not a long text'.split() 
print(word_list) 

word_with_position = [ 
    (word, float(i)/len(word_list)) for i, word in enumerate(word_list)] 
print(word_with_position) 

結果:Dictのよう

['Here', 'is', 'a', 'text', 'it', 'is', 'not', 'a', 'long', 'text'] 

[('Here', 0.0), ('is', 0.1), ('a', 0.2), ('text', 0.3), ('it', 0.4), 
('is', 0.5), ('not', 0.6), ('a', 0.7), ('long', 0.8), ('text', 0.9)] 

from collections import defaultdict 

word_with_positions = defaultdict(list) 
for i, word in enumerate(word_list): 
    word_with_positions[word].append(float(i)/len(word_list)) 

print(word_with_positions) 

結果:

{'a': [0.2, 0.7], 'text': [0.3, 0.9], 'is': [0.1, 0.5], 'it': [0.4], 
'Here': [0.0], 'long': [0.8], 'not': [0.6]} 
+0

ニース。さて、これを試して、タプルのリストをコンパイルして、各単語が複数の場所のリストに1回しか表示されないようにするかどうかを見てみましょう - 私は1つのテキストまたは全体のコーパス。 –

+1

あなたは私にそれを打つ。アンスタンプをありがとう! –

関連する問題