簡體   English   中英

從數字 Python 之前的字符串中提取單詞

[英]Extract words from string before number Python

大家好,我想知道是否可以在 python 中從數字之前的字符串中提取單詞。

例如:

Hi my name is hazza 50 test test test

Hi hazza 60 test test test

hazza 50 test test test

如果可能的話,我想得到數字之前的單詞而不是之后的單詞。

Hi my name is hazza

Hi hazza

hazza

問候哈扎

正則表達式會做

import re

strings = '''
Hi my name is hazza 50 test test test

Hi hazza 60 test test test

hazza 50 test test test

hazza test test test
'''

for s in re.findall('([a-zA-Z ]*)\d*.*',strings):
    print(s)

Hi my name is hazza 

Hi hazza 

hazza 

hazza test test test
is_digit = False
str = "Hi my name is hazza 50 test test test"
r = 0

for c in str:
  if c.isdigit():
     # is_digit = True
     r = str.index(c)

print(str[0:r-2])

r 是 5 r-2 的索引,因為您希望字符串在 50 之前沒有那個空格

閱讀: https://www.learnpython.org/

s = "Hi my name is hazza 50 test test test"
result = ""
for i, char in enumerate(s):
    if char.isdigit():
        result = s[:i]
        break
print(result)

此實現將允許您提取字符串中每個數字之前的所有單詞集。

s = '50 Hi hazza 60 test test 70 test'
# Split string on spaces
split = s.split()
# Instantiate list to hold words
words = []
curr_string = ''
for string in split:
    # Check if string is numeric value
    if string.isnumeric():
        # Catch edge case where string starts with number
        if curr_string != '':
            # Add curr_string to words list -- remove trailing whitespace
            words.append(curr_string.strip())
            curr_string = ''
    else:
        # If string not numeric, add to curr_string
        curr_string += string + ' '

print(words)

Output: ['Hi hazza', 'test test']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM