小编Gal*_*are的帖子

如何检查字符串是否与Python中的设置模式匹配?

我想将字符串与特定模式或单词集匹配,如下所示:

the apple is red是查询, the apple|orange|grape is red|orange|violet是匹配的模式.管道将代表相互替代的单词.该模式也可以分组为[launch app]|[start program].我希望模块返回True或False,无论查询是否与模式匹配,当然.

如果没有可以执行此操作的库,那么实现此目的的最佳方法是什么?如果这可以用简单的正则表达式完成,那就太好了; 但我对正则表达式几乎一无所知.我使用的是Python 2.7.11

python string pattern-matching

4
推荐指数
1
解决办法
6909
查看次数

Python:创建一个空文件对象

我试图为Python创建一个无法正常工作的日志记录模块,因为它无法创建文件对象.

debug.py:

import os
import datetime
import globals

global fil
fil = None

def init(fname):
     fil = open(fname, 'w+')
     fil.write("# PyIDE Log for" + str(datetime.datetime.now()))

def log(strn):
    currentTime = datetime.datetime.now()

    fil.write(str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn)
    print str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn

def halt():
    fil.close()
Run Code Online (Sandbox Code Playgroud)

fil不会None像我得到的那样工作AttributeError.我也试过创建一个虚拟对象:

fil = open("dummy.tmp","w+")
Run Code Online (Sandbox Code Playgroud)

但是dummy.tmp文件被写入,即使init()之前log()被调用了.显然,您无法在已打开的文件上打开新文件.我试图关闭fil之前init(),但Python说它无法write()在关闭的文件上执行.

这是正在访问的代码 debug.py

if …
Run Code Online (Sandbox Code Playgroud)

python file-io python-2.7

2
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×2

file-io ×1

pattern-matching ×1

python-2.7 ×1

string ×1