gpt4 book ai didi

Python:获取项目位置作为列表索引除以长度的百分比

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:28 37 4
gpt4 key购买 nike

我有一组文本。这些文本中的每一个都被标准化并标记为一个列表——我将在下面发布该代码——这样我所拥有的是一个列表列表,每个列表都是一个文本。我想要做的是获取文本中每个单词的所有位置。

例如,“这是一段文本;它不是一个长文本。”

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

最佳答案

如果您枚举列表,那么您就有了索引,并且可以除以长度以获得相对位置:

代码:

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)

结果:

['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]}

关于Python:获取项目位置作为列表索引除以长度的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43771328/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com