Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split list by multiple separators

Tags:

python

list

If I have a sentense like that:

text = "The sun shine brightly, but is very cold today!"

I can use the split:

newArray = text.split(" ")
print (newArray)   

End the result, will be:

['The', 'sun', 'shine', 'brightly,', 'but', 'is', 'very', 'cold', 'today!']

But, If I need to separate not just only with "Space" but for example "Space", "comma" and "Enter".

How can I do that?

To be more clear, here is my Code example:

import io
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage
import re

def extract_text_from_pdf(pdf_path):
    resource_manager = PDFResourceManager()
    fake_file_handle = io.StringIO()
    converter = TextConverter(resource_manager, fake_file_handle)
    page_interpreter = PDFPageInterpreter(resource_manager, converter)
    with open(pdf_path, 'rb') as fh:
        for page in PDFPage.get_pages(fh, 
                                      caching=True,
                                      check_extractable=True):
            page_interpreter.process_page(page)
        text = fake_file_handle.getvalue()
    # close open handles
    converter.close()
    fake_file_handle.close()
    if text:
        return text


text = extract_text_from_pdf('file.pdf')
newArray = text.split(" ")
print (newArray)   
like image 661
Davi Amaral Avatar asked Jan 20 '26 22:01

Davi Amaral


2 Answers

You could use re.split in order to split by multiple criteria:

text = "The sun shine brightly, but is very cold today!"

Say you want to split by spaces and commas:

import re
re.split( r'\s+|,\s*', text)
# ['The', 'sun', 'shine', 'brightly', 'but', 'is', 'very', 'cold', 'today!']
like image 116
yatu Avatar answered Jan 22 '26 10:01

yatu


The simplest approach would probably be to normalize your data, and replace all the "comma" and "enter"s with space, then split as you did before or use split() from re with \s meta.

like image 26
Marcin Orlowski Avatar answered Jan 22 '26 10:01

Marcin Orlowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!