python - 用于返回系列中的元素的 Python 代码
问题描述
我目前正在为抓取推文的主题建模编写一个脚本,但我遇到了几个问题。我希望能够搜索一个单词的所有实例,然后返回该单词的所有实例,加上之前和之后的单词,以便为单词的使用提供更好的上下文。
我已经标记了所有推文,并将它们添加到一个系列中,其中相对索引位置用于识别周围的单词。
我目前拥有的代码是:
myseries = pd.Series(["it", 'was', 'a', 'bright', 'cold', 'day', 'in', 'april'],
index= [0,1,2,3,4,5,6,7])
def phrase(w):
search_word= myseries[myseries == w].index[0]
before = myseries[[search_word- 1]].index[0]
after = myseries[[search_word+ 1]].index[0]
print(myseries[before], myseries[search_word], myseries[after])
该代码大部分都有效,但如果搜索第一个或最后一个单词,则会返回错误,因为它超出了 Series 的索引范围。有没有办法忽略超出范围的索引并简单地返回范围内的内容?
当前代码也只返回搜索词前后的词。我希望能够在函数中输入一个数字,然后返回之前和之后的一系列单词,但我当前的代码是硬编码的。有没有办法让它返回指定范围的元素?
我在创建循环来搜索整个系列时也遇到问题。根据我写的内容,它要么返回第一个元素而不返回其他任何内容,要么一遍又一遍地重复打印第一个元素,而不是继续搜索。不断重复第一个元素的有问题的代码是:
def ws(word):
for element in tokened_df:
if word == element:
search_word = tokened_df[tokened_df == word].index[0]
before = tokened_df[[search_word - 1]].index[0]
after = tokened_df[[search_word + 1]].index[0]
print(tokened_df[before], word, tokened_df[after])
显然,我忽略了一些简单的事情,但我一生都无法弄清楚它是什么。如何修改代码,以便如果在系列中重复相同的单词,它将返回单词的每个实例以及周围的单词?我希望它的工作方式遵循“如果条件为真,则执行“短语”功能的逻辑,如果不为真,则继续执行该系列。
解决方案
像这样的东西?我在您的示例中添加了一个重复的词(“明亮”)。还添加n_before
并n_after
输入周围单词的数量
import pandas as pd
myseries = pd.Series(["it", 'was', 'a', 'bright', 'bright', 'cold', 'day', 'in', 'april'],
index= [0,1,2,3,4,5,6,7,8])
def phrase(w, n_before=1, n_after=1):
search_words = myseries[myseries == w].index
for index in search_words:
start_index = max(index - n_before, 0)
end_index = min(index + n_after+1, myseries.shape[0])
print(myseries.iloc[start_index: end_index])
phrase("bright", n_before=2, n_after=3)
这给出了:
1 was
2 a
3 bright
4 bright
5 cold
6 day
dtype: object
2 a
3 bright
4 bright
5 cold
6 day
7 in
dtype: object
推荐阅读
- scala - 杜比。编写 .update.withGeneratedKeys() 和 .update.run
- json - 从 Map 的结构中保存读/写/保存到 json
- jsf - 删除最后一页 LazyDataModel 中的最后一行
- firebase-realtime-database - Firebase 实时数据库:用户是否每次都下载整个数据库?
- algorithm - COLCOIN - 收集硬币
- r - 如何在R中的ggradar中填充雷达图的多边形
- reactjs - 在页面加载时触发 React Apollo 突变
- python-3.x - HTTP/1.1 客户端:如何确定好的保持活动超时默认值?
- c# - 有没有办法知道控制流去的所有行号?
- c# - 如何使用 DataGrid C# WPF 更新数据库?