Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i separate float numbers from a .docx file and add it to a list?

 from docx import Document
    numbers = []
    doc = Document('word.docx')
    for para in doc.paragraphs:
        new_text = para.text
        for char in new_text:
            if char in '0123456789.':
                numbers.append(char)
        print(new_text)
    
    print(numbers)

*its a persian language docx file

it return this:

بزرگترین جانور از تیرهٔ و بومی آسیا است که طول بدن آن به 2.7 تا 3 متر و وزن آن به 306 می‌رسد. مهم‌ترین مشخصهٔ این جانور، خط‌های عمودی تیره روی خز قرمز-نارنجی آن است که در ناحیهٔ زیرین روشن‌تر است. این جانور دارای بدنی عضلانی و پاهایی بسیار نیرومند است. بدن ببر دارای موهای بلند و برّاق به رنگ ، همراه با خط‌های سیاه عمودی می‌باشد. جثّهٔ ببرهای نر بزرگ‌تر از ببرهای ماده است و همچنین موهای روی گونهٔ ببر نر بلندتر از ببر ماده می‌باشد. دندان‌های ببر بسیار قوی است و در میان جانوران خشکی بلندترین است. طول ببر به 74.5 میلی‌متر و گاهی تا 90 میلی‌متر می‌رسد.
در ببرها معمولاً بین 10تا15 سال عمر می‌کنند. بیشترین طول عمر ثبت شده در باغ‌ وحش‌ها 26 سال گزارش شده‌است.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[‘2’, ‘.’, ‘7’, ‘3’, ‘3’, ‘0’, ‘6’, ‘.’, ‘.’, ‘.’, ‘.’, ‘.’, ‘.’, ‘7’, ‘4’, ‘.’, ‘5’, ‘9’, ‘0’, ‘.’, ‘1’, ‘0’, ‘1’, ‘5’, ‘.’, ‘2’, ‘6’, ‘.’]

as you can see it add periods of text to list as well.

>Solution :

Of course it captures all periods, since you allow them in your character list. To recognize numbers, you can’t just inspect individual characters, though, but groups of them. You can do that rather simply by using regular expressions:

In [7]: re.findall("\d+(?:\.\d+)?", text)
Out[7]: ['2.7', '3', '306', '74.5', '90', '10', '15', '26']

(That’s just an example, in reality you would need to find a pattern matching your use case and should compile it before usage with re.compile.)

Then you just need to convert the results:

In [8]: [float(x) for x in re.findall("\d+(?:\.\d+)?", text)]
Out[8]: [2.7, 3.0, 306.0, 74.5, 90.0, 10.0, 15.0, 26.0]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading