0

I'm using Python's NLP library - Spacy. I'm trying to replace noun chunks in an article. Noun chunks look like this: 'the most secure facial recognition'. I would like to replace them by something like this: 'the_most_secure_facial_recognition' (underlines instead of spaces)

So I wrote this piece of code:

import spacy

nlp = spacy.load('en_core_web_md')

data =  "In the end, the notch was a relatively useless design trend for Android phones, and consumers were left " \
        "wanting. The hole-punch camera seems to be a better answer. Here's a new idea that looks genuinely futuristic " \
        "and hasn't been pulled off by Apple yet. It's an admission that Face ID is difficult to clone, a hole-punch " \
        "won't include all the fancy sensors required for the most secure facial recognition, but consumers probably " \
        "don't care that much, anyway. There's always a fingerprint sensor, after all."

doc = nlp(data)

# doc2 = doc.text
doc2 = str(doc)

for nc in doc.noun_chunks:
    old_nc = str(nc)
    new_nc = old_nc.replace(' ', '_')
    print(old_nc)
    print(new_nc)
    doc2.replace(old_nc, new_nc)

print(doc2)

When I run it, nothing is replaced in doc2. Am I doing something wrong?

Andrey Kurnikovs
  • 407
  • 1
  • 5
  • 21

1 Answers1

3

replace doesn't modify the existing string, but instead returns a new string.

So this won't work:

doc2.replace(old_nc, new_nc)

But this will:

doc2 = doc2.replace(old_nc, new_nc)

This is the relevant documentation:

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

https://docs.python.org/3/library/stdtypes.html#str.replace

Nikolas Stevenson-Molnar
  • 4,235
  • 1
  • 22
  • 31