python - 在Python中使用正则表达式

标签 python

我尝试在 python 脚本中使用正则表达式,但没有成功。

我有一个 python 脚本,它会获取 txt 文件中的这些数据并传输到 csv 文件:

txt 文件中的示例数据

  0.0 testing_1
  1.0 testing_2
 -5.0 testing_3
  4.5 testing_4  

我想对包含一个空格、另一个空格或破折号、数字和点的行的前 4 个字符使用正则表达式。正则表达式示例:(|-)\d。我想使用正则表达式,因为字符正在改变,但它不起作用。

这是我的代码:

import csv
import re

# open and read the txt file.
text_file = open("extractspamreport.txt", "r")

# Read each line of text file and save it in lines. 
lines = text_file.readlines()

# Make a csv file.
mycsv = csv.writer(open('OutPut.csv', 'w'))

# Write header for csv file.
mycsv.writerow(['Rule Name'])
mycsv.writerow(['Points'])

#problem starts here
testvar = re.search(" ( |-)\d+.", lines)

n = 0
for line in lines: 
    n = n + 1
n = 0
for line in lines: 
    n = n + 1
    if testvar in line:
        #this is just for checking if the regex is correct
        print("hello world")

错误如下:

Traceback (most recent call last):

  File "test2.py", line 24, in <module>

  testvar = re.search(" ( |-)\d+.", lines)

  File "C:\Users\testf\AppData\Local\Programs\Python\Python35\lib\re.py", line 173, in search

  return _compile(pattern, flags).search(string)

TypeError: expected string or bytes-like object

有什么方法可以使用正则表达式获取该数据吗?

最佳答案

好吧..首先问题是您没有将正确类型的参数传递给re.search()

readlines() 返回一个列表而不是字符串,所以..

行==列表

阅读线

https://www.tutorialspoint.com/python/file_readlines.htm

加入

https://www.geeksforgeeks.org/join-function-python/

所以让我们修复它。 使用 Join 将列表传递给字符串

让我们使用re.findall()来获取所有匹配项

您可以复制并粘贴此代码以测试其是否有效

Repl.it - Online Python Editor and IDE <-已经有了代码

如果你想重现错误,只需将 re.findall() 中的“string”更改为“lines”

import re

lines = ["-5.0 testing_3"," 1.0 testing_2"," 0.0 testing_2"]
separator = "," #or any other separator u want to the string u can use espace too
string = separator.join(lines)
 #join() is used here to transform a list in a string     
result = re.findall("( \d+|-\d+).",string)
print(result) 
 #the group is the string matched by () on regex and if u
 #create more ()"groups" u can use group(1) and so on

'''
#the result 
>>>['-5', ' 1', ' 0']

'''

如果你想在字符串上使用变量,就像这样简单

"{}{}{}".format(var1,var2,var3) #each {} is one var

关于python - 在Python中使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57949924/

相关文章:

Python,使用 lambda、map 和 filter

python - 有没有办法延迟向量化给定的类?

python - 降低图像分辨率

python - 在鲁梅尔往返时保留长单线字符串

python - pycrypto : No module named strxor

python - Ubuntu vs OSX 和 SSD vs HDD 上的多处理

python - 在 3D 中绘制正态分布

python - 我如何从标准输入读取?

python - 如何使用 Sphinx 链接到 str 方法?

python - 在 Django 模板上对许多变量/字典使用 "context"的最佳方法