【问题标题】:Extract numbers enclosed in【 】which are of different length?提取【 】中不同长度的数字?
【发布时间】:2020-03-14 18:47:41
【问题描述】:

如何更改我的代码参数以提取【】中长度不同的数字? 我有一个df存储这种格式的数字【123】。但是,df["News"] 中的数字的长度不同,如下所示:

df[“新闻”]:

【123】text text , 
【1234】text text text , 
【1】text text text... 

我的代码:

df['num'] = df['News'].str.extract('(\d{4})')

期望的输出:

123
1234
1

【问题讨论】:

  • str.extract('(\d+)') ?
  • 谢谢。代码提取了数字。怎么把提取限制在【】内,因为【】外还有其他数。

标签: python regex string pandas extract


【解决方案1】:

使用:.str.extract('(【\d+】)')

例如:

df = pd.DataFrame({"News":['【123】text text 123', '【1234】text text text 2344, kkk', '【1】text text text 09ekk']})
df['num'] = df['News'].str.extract('(【\d+】)')
#or
df['num_1'] = df['News'].str.extract('【(\d+)】')
print(df)

输出:

                             News     num num_1
0              【123】text text 123   【123】   123
1  【1234】text text text 2344, kkk  【1234】  1234
2         【1】text text text 09ekk     【1】     1

【讨论】:

  • 有些词条是这样的【abc】text text text 456 text 因此,需要将搜索限制在【】内。怎么做?谢谢。
【解决方案2】:

演示:

import re
s = '''【123】text text , 
【1234】text text text , 
【1】text text text... ,
【abc】text text text 456 text'''

reg = '【(\w+)】'

for i in s.split('\n'):
    r = re.search(reg, i)
#     print(i, r)
    if r:
        print(r.group(1))

输出

123
1234
1
abc

【讨论】:

  • 有些词条是这样的【abc】text text text 456 text 因此,需要将搜索限制在【】内。谢谢。
  • 可能是这样的?
  • 谢谢。我尝试在我的 df 上应用并添加此代码 s = df['News'],出现错误“'Series' object has no attribute 'split'”>。如果需要对 df 列执行提取,需要进行哪些修改?
  • 你可以直接使用代码:df['num'] = df['News'].str.extract('【(\w+)】'),修改reg
猜你喜欢
  • 2018-09-16
  • 2015-01-07
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 2016-09-23
  • 1970-01-01
  • 2021-02-20
  • 2020-02-06
相关资源
最近更新 更多