小编Lud*_*sed的帖子

Python正则表达式匹配字符串末尾的标点符号

如果句子以大写字母开头并以Python中的[?.!]结尾,我需要匹配.

编辑它必须在结尾处有[?.!] 但在句子中允许其他标点符号

import re
s = ['This sentence is correct.','This sentence is not correct', 'Something is !wrong! here.','"This is an example of *correct* sentence."']

# What I tried so for is:
for i in s:
    print(re.match('^[A-Z][?.!]$', i) is not None)
Run Code Online (Sandbox Code Playgroud)

它不起作用,经过一些更改我知道该^[A-Z]部分是正确的但最后匹配标点符号是不正确的.

python regex match python-3.x

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

python使用正则表达式交换单词

今天,我正在学习很多正则表达式,但是我已经陷入了困境。我正在尝试在python中使用正则表达式交换单词,但似乎无法弄清楚。

s = 'How are you guys today'
# This is what I tried so far, but i obviously miss something 
# because this is giving an IndexError: no such group
re.sub(r'\w+\w+', r'\2\1', s)
Run Code Online (Sandbox Code Playgroud)

预期结果

'are How guys you today'
Run Code Online (Sandbox Code Playgroud)

python regex substitution

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

从numpy数组中获取第n个元素

假设我有一个 rgb-imagetype 的 numpy 数组,如下所示:

d = [ [ [0, 1, 2],    [3, 4, 5],    [6 ,7 ,8] ], 
      [ [9, 10, 11], [12, 13, 14], [15, 16 ,17] ],
      [ [18,19, 20], [21, 22, 23], [24, 25 ,26] ] ]
Run Code Online (Sandbox Code Playgroud)

我使用以下命令选择一些随机的 r/g 或 b 像素random

import random
r = random.sample(range(1, len(d)*len(d[0])*3), 3)
# for example r = [25, 4, 15]
Run Code Online (Sandbox Code Playgroud)

那么我该如何选择我想要的数据呢?

就像我想要25th value in array d第一个r_value = 25对应于 的值一样d[2][2][1],因为它是第 25 个值。

python arrays numpy

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

Python Cryptography模块将RSA密钥保存/加载到文件中

使用Python 的Cryptography模块,

我想将生成的私钥保存在文件中,以便稍后使用.

但是从文档中我无法找到所需的方法.

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding

# Working RSA encryption you can run for yourself
MESSAGE = 'I am a very secret message'

# Create private key
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)

# Create public key
public_key = private_key.public_key()

# Encrypt
ciphertext = public_key.encrypt(
    MESSAGE,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
        algorithm=hashes.SHA1(),
        label=None
    )
)

# Encrypted text
print ciphertext

# Decrypt …
Run Code Online (Sandbox Code Playgroud)

python cryptography rsa

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

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