Python Forum
Finding a number in a file printing out number and next word
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Finding a number in a file printing out number and next word
#1
Hi,
I am in Need of a little help. I wish to search within a text file and retrieve into another text file. The numbers and the words that appear after the numbers.
for example:
We have 40 white candies, 24 green ones, 12 red ones, 24 yellow ones and 20 blue ones.
40 white
24 green
12 red
24 yellow
20 blue
I managed to isolate the numbers - but I have confounded myself on how to grab the next word after the number.

# Import the regular expression module
import re

# Find the numeric values: matches
matches = re.findall('\d+', 'We have 40 white candies, 24 green ones, 12 red ones, 24 yellow ones and 20 blue ones.')

# Print the matches
print(matches)
RESULT
['40', '24', '12', '24', '20']
Reply
#2
Match the whitespace(\s) and word(\w+) after numbers
>>> import re
>>> 
>>> matches = re.findall(r'\d+\s\w+', 'We have 40 white candies, 24 green ones, 12 red ones, 24 yellow ones and 20 blue ones.')
>>> matches
['40 white', '24 green', '12 red', '24 yellow', '20 blue']
Reply
#3
Thank you - so appreciated
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Music Python Script Repeating Number When Saving Facebook Photos ThuanyPK 2 221 May-13-2024, 10:59 PM
Last Post: ebn852_pan
  intering int number akbarza 1 351 Apr-28-2024, 08:55 AM
Last Post: Gribouillis
Brick Number stored as text with openpyxl CAD79 2 674 Apr-17-2024, 10:17 AM
Last Post: CAD79
  [SOLVED] Pad strings to always get three-digit number? Winfried 2 467 Jan-27-2024, 05:23 PM
Last Post: Winfried
  Prime number detector Mark17 5 930 Nov-27-2023, 12:53 PM
Last Post: deanhystad
  Create X Number of Variables and Assign Data RockBlok 8 1,138 Nov-14-2023, 08:46 AM
Last Post: perfringo
  find the sum of a series of values that equal a number ancorte 1 573 Oct-30-2023, 05:41 AM
Last Post: Gribouillis
  Replace a text/word in docx file using Python Devan 4 4,075 Oct-17-2023, 06:03 PM
Last Post: Devan
  capturing multiline output for number of parameters jss 3 898 Sep-01-2023, 05:42 PM
Last Post: jss
  Sequential number for rows retrieved and storing the Primary UKey to the line number GYKR 2 652 Aug-22-2023, 10:14 AM
Last Post: GYKR

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020