2

I have a String

c=("Snap-on Power M1302A5 Imperial,IMPRL 0.062IN")

and I need to convert above string to

c=("Snap-on Power Imperial,IMPRL")

i.e i need to remove string that has both letters and numbers,

How can I do this in python?

I tried with

c=c.apply(word_tokenize)
c = c.apply(lambda x: [item for item in x if item.isalpha()])

but got output

c=("Snap-on Power MA Imperial,IMPRL IN")
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Ranjana Girish
  • 473
  • 7
  • 17

5 Answers5

5

I'm not sure exactly what you want here, but it seems you want to remove words that have a digit in them. In that case, you can use any() here:

>>> c = "Snap-on Power M1302A5 Imperial,IMPRL 0.062IN"
>>> ' '.join(w for w in c.split() if not any(x.isdigit() for x in w))
Snap-on Power Imperial,IMPRL
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
3

Also adding a regex based solution:

c = "Snap-on Power M1302A5 Imperial,IMPRL 0.062IN"
only_a = []
for word in c.split():
    #print(word)
    if not re.search('\d',word):
        #print(word)
        only_a.append(word)
' '.join(only_a)

Output: 'Snap-on Power Imperial,IMPRL'

Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73
amrrs
  • 6,215
  • 2
  • 18
  • 27
1

To select words without digit

c = ' '.join([item for item in c.split() if not any(filter(str.isdigit, item))])
# ['Snap-on', 'Power', 'Imperial,IMPRL']
splash58
  • 26,043
  • 3
  • 22
  • 34
1

This answer does the same thing as other answers

Step 1: Split the string into different words

Step 2: Check if each word contains numbers, if it does skip the word

Step 3: Generate a string from the words without numbers

line = "Snap-on Power M1302A5 Imperial,IMPRL 0.062IN"

split_line = line.split(" ")

final_split_string = []

for word in split_line:
    skip_word = False
    for letter in word:
        if letter.isdigit():
            #check if the current word contains a number
            skip_word = True

    if not skip_word:
        #skip a word if it contains number
        final_split_string.append(word)

final_string = " ".join(final_split_string)
Anuj
  • 994
  • 11
  • 21
0

You can try something like this:

c="Snap-on Power M1302A5 Imperial,IMPRL 0.062IN"
import re
pattern=r'\d'

final=[]
for i in c.split():
    if isinstance(i.split(','),list):
        for m in i.split(','):
            if re.search(pattern,m):
                pass
            else:
                final.append(m)

print(" ".join(final))

output:

Snap-on Power Imperial IMPRL