[英]Python - Extract hashtags from text; end at punctuation
对于我的编程类,我必须根据以下描述创建一个函数:
该参数是推文。 此函数应返回一个列表,其中包含推文中所有主题标签的排列顺序(按它们在推文中出现的顺序)。 返回列表中的每个主题标签都应删除初始的哈希符号,并且主题标签应唯一。 (如果一条tweet两次使用相同的#标签,则该列表仅包含一次。#标签的顺序应与tweet中每个标签的首次出现的顺序相匹配。)
我不确定如何创建标签,以便在遇到标点符号时结束主题标签(请参阅第二个doctest示例)。 我当前的代码未输出任何内容:
def extract(start, tweet):
""" (str, str) -> list of str
Return a list of strings containing all words that start with a specified character.
>>> extract('@', "Make America Great Again, vote @RealDonaldTrump")
['RealDonaldTrump']
>>> extract('#', "Vote Hillary! #ImWithHer #TrumpsNotMyPresident")
['ImWithHer', 'TrumpsNotMyPresident']
"""
words = tweet.split()
return [word[1:] for word in words if word[0] == start]
def strip_punctuation(s):
""" (str) -> str
Return a string, stripped of its punctuation.
>>> strip_punctuation("Trump's in the lead... damn!")
'Trumps in the lead damn'
"""
return ''.join(c for c in s if c not in '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
def extract_hashtags(tweet):
""" (str) -> list of str
Return a list of strings containing all unique hashtags in a tweet.
Outputted in order of appearance.
>>> extract_hashtags("I stand with Trump! #MakeAmericaGreatAgain #MAGA #TrumpTrain")
['MakeAmericaGreatAgain', 'MAGA', 'TrumpTrain']
>>> extract_hashtags('NEVER TRUMP. I'm with HER. Does #this! work?')
['this']
"""
hashtags = extract('#', tweet)
no_duplicates = []
for item in hashtags:
if item not in no_duplicates and item.isalnum():
no_duplicates.append(item)
result = []
for hash in no_duplicates:
for char in hash:
if char.isalnum() == False and char != '#':
hash == hash[:char.index()]
result.append()
return result
在这一点上我很迷茫。 任何帮助,将不胜感激。 先感谢您。
注:我们是不允许使用正则表达式或进口任何模块。
您看起来确实有些迷路。 解决这类问题的关键是将问题分成较小的部分,加以解决,然后将结果合并。 您已拥有所需的每一块..:
def extract_hashtags(tweet):
# strip the punctuation on the tags you've extracted (directly)
hashtags = [strip_punctuation(tag) for tag in extract('#', tweet)]
# hashtags is now a list of hash-tags without any punctuation, but possibly with duplicates
result = []
for tag in hashtags:
if tag not in result: # check that we haven't seen the tag already (we know it doesn't contain punctuation at this point)
result.append(tag)
return result
ps:这是一个非常适合正则表达式解决方案的问题,但是如果您想要快速的strip_punctuation
,则可以使用:
def strip_punctuation(s):
return s.translate(None, '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.