【问题标题】:Extract words from string before number Python从数字Python之前的字符串中提取单词
【发布时间】:2020-06-19 16:58:54
【问题描述】:

大家好,我想知道在 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

问候 哈扎

【问题讨论】:

  • 当然,有很多方法可以做到这一点。您可能想研究正则表达式。如果数字前后总是有空格,您还可以使用str.split()str.isdigit() 以及for 循环。

标签: python python-3.x string numbers


【解决方案1】:

正则表达式会做

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

【讨论】:

  • 快速提问,我一直在使用它来遍历我的数据,但我遇到了一些条目没有数字的问题。有没有办法解决这个问题。如果有新行,我尝试使用 elif 语句删除其余单词。
  • 新编辑的代码应该可以工作,试试@TheAmazingHAzza
  • 非常感谢新编辑的答案,这对我有很大帮助。再次感谢!
【解决方案2】:
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/

【讨论】:

    【解决方案3】:
    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)
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    【解决方案4】:

    此实现将允许您提取字符串中每个数字之前的所有单词集。

    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)
    

    输出: ['Hi hazza', 'test test']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多