NLP: Hashtags and mentions

Extract the hashtags and mentions from social media posts.

What to build

A program that lists the distinct hashtags and mentions found in several posts.

Requirements

  • A hashtag is # followed by one or more word characters (\w); a mention is @ followed by word characters. The # or @ must be at the start of the line or right after whitespace, so ana@uni.edu and issue#4 do not count.
  • Lowercase what you find and keep each one once, in order of first appearance.
  • Print hashtags: ... and mentions: ..., with the items separated by spaces, or none.

Input

Line 1: n. Then n posts, one per line.

Output

Two lines.

Constraints

n ≤ 100; each post has at most 300 characters.

Example

Input:

2
Loving #NLP with @ana! #python
@Bo thanks, #nlp rocks

Output:

hashtags: nlp python
mentions: ana bo

Why it works

The lookbehind ties each symbol to the start of a word, which is exactly what separates a hashtag or a mention from an email address or an issue number.

Examples

Example 1 · Input
2
Loving #NLP with @ana! #python
@Bo thanks, #nlp rocks
Expected output
hashtags: nlp python
mentions: ana bo
Example 2 · Input
1
Write to ana@uni.edu about issue#4
Expected output
hashtags: none
mentions: none

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

`(?<!\S)` means "not preceded by a non-space character": the match starts the line or follows whitespace.

Hint 2

`re.findall(r"(?<!\S)#(\w+)", line)` returns the words after each hashtag symbol.

Solution

Show one correct solution (try it yourself first)
import re

tags, users = [], []
for _ in range(int(input())):
    line = input()
    for t in re.findall(r"(?<!\S)#(\w+)", line):
        if t.lower() not in tags:
            tags.append(t.lower())
    for u in re.findall(r"(?<!\S)@(\w+)", line):
        if u.lower() not in users:
            users.append(u.lower())
print("hashtags:", " ".join(tags) if tags else "none")
print("mentions:", " ".join(users) if users else "none")

Lesson: Regular expressions for text →