【问题标题】:Matching Keywords in a List to a Line of Words in Python将列表中的关键字与 Python 中的一行单词匹配
【发布时间】:2017-11-15 02:36:52
【问题描述】:

以下是我需要从中分析和提取特定单词的多行示例中的两个示例。

[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl


[37.786221300000001, -122.1965002] 6 2011-08-28 19:55:26 I wish I could lay up with the love of my life And watch cartoons all day.

坐标和数字被忽略

案例是找出每条推文中的单词有多少出现在这个关键字列表中:

['hate', 1]
['hurt', 1]
['hurting', 1]
['like', 5]
['lonely', 1]
['love', 10]

另外,求每条推文行中关键字的值的总和(例如 ['love', 10])。

例如,对于句子

'I hate to feel lonely at times'

hate=1lonely=1 的情绪值之和等于 2。 没有。该行中的单词数为 7。

我尝试使用 list into lists 方法,甚至尝试遍历每个句子和关键字,但这些都没有奏效,因为没有。推文和关键字有几个,我需要使用循环格式来查找值。

提前欣赏您的见解! :)

我的代码:

try:
    KeywordFileName=input('Input keyword file name: ')
    KeywordFile = open(KeywordFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()
KeyLine = KeywordFile.readline()
while KeyLine != '':
    if list != []:
        KeyLine = KeywordFile.readline()
        KeyLine = KeyLine.rstrip()
        list = KeyLine.split(',')
        list[1] = int(list[1])
        print(list)
    else:
        break

try:
    TweetFileName = input('Input Tweet file name: ')
    TweetFile = open(TweetFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()

TweetLine = TweetFile.readline()
while TweetLine != '':
    TweetLine = TweetFile.readline()
    TweetLine = TweetLine.rstrip()

【问题讨论】:

  • 请发布您的代码。
  • 我已经添加了我的代码。

标签: python string list loops integer


【解决方案1】:

您可以使用简单的正则表达式来提取单词并使用分词器来计算每个单词在示例字符串中出现的次数。

from nltk.tokenize import word_tokenize
import collections
import re

str = '[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl'
num_regex = re.compile(r"[+-]?\d+(?:\.\d+)?")
str = num_regex.sub('',str)
words = word_tokenize(str)
final_list = collections.Counter(words)
print final_list

【讨论】:

    猜你喜欢
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多