【问题标题】:Python CSV Regex All Columns And Output Column List Index Number Based On Most Regex Matches基于大多数正则表达式匹配的 Python CSV 正则表达式所有列和输出列列表索引号
【发布时间】:2020-11-25 05:35:18
【问题描述】:

嘿,我真的被困住了,我真的希望有人可以帮助我。我正在尝试读取 CSV 文件的前 5000 行,通过制表符分隔符拆分行,然后针对每一列和每一行搜索正则表达式模式,并输出具有最多正则表达式匹配/出现的列索引号。我将提供一个示例来帮助更好地解释我的意思。

test.csv

john smith  1132 Anywhere Lane Hoboken NJ   10.0.0.1     07030  Jan 4
erica meyers    1234 Smith Lane Hoboken NJ  127.0.0.1    07030  March 2
erica meyers    1234 Smith Lane Hoboken NJ  192.168.1.1  07030  april 5

这是我目前所在的位置(读取 csv,按制表符分隔成列,打印前 100 行):

import csv
import re
        
Num = 5000
        
with open('test.csv', newline='', encoding="cp437", errors='ignore') as csvfile:
    reader = csv.reader(csvfile, delimiter='\t')
    for i in range(Num):
        lines = next(reader)

当前输出的前几行:

['john smith', '1132 Anywhere Lane Hoboken NJ', '10.0.0.1', ' 07030', 'Jan 4']
['john smith', '1234 Smith Lane Hoboken NJ', '127.0.0.1', ' 07030', 'March 2']
['smith john', '1234 Smith Lane Hoboken NJ', '192.168.1.1', ' 07030', 'april 5']

这是我卡住的地方......

我想针对每一行的所有列搜索正则表达式\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3},并输出与正则表达式匹配最多的列索引号。

对于此示例,\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} 将匹配

10.0.0.1
127.0.0.1
192.168.1.1

所以我想要的输出是:

2

【问题讨论】:

  • 为什么不用熊猫?

标签: python python-3.x


【解决方案1】:

你可以用这样的熊猫来做到这一点

df=pd.read_csv(path, nrows=5000, sep="\t")

编写一个函数来检查正则表达式是否匹配。

def check_regex_matches(x):
    
    return bool(re.match(regex, x))

然后就可以使用了

list_of_bools_where_regex_matches = df["some_col"].apply(lambda
 x:check_regex_match(x))

df["some_col"][list_of_bools_where_regex_matches].index 

注意: 请检查您是否需要 re.match 或 re.search https://stackoverflow.com/a/12595082/4213362

【讨论】:

猜你喜欢
  • 2013-05-12
  • 2018-01-08
  • 2013-02-28
  • 1970-01-01
  • 2019-05-23
  • 1970-01-01
  • 2015-03-26
  • 1970-01-01
  • 2011-06-03
相关资源
最近更新 更多