python2,将list中的字符串与文件中进行匹配,如果没有匹配上,进行记录
时间: 2024-03-17 13:42:35 浏览: 21
好的,可以使用Python2中的正则表达式(re模块)进行字符串匹配,并使用Python2中的open函数打开文件进行读取和写入。代码示例如下:
```python
import re
# 打开文件
with open('file.txt', 'r') as f:
file_content = f.read()
# 待匹配的字符串列表
str_list = ['str1', 'str2', 'str3']
# 匹配模式
pattern = '|'.join(str_list)
# 在文件中查找匹配项
match_result = re.findall(pattern, file_content)
# 如果没有匹配上,记录到文件中
if not match_result:
with open('not_matched.txt', 'a') as f:
f.write(','.join(str_list) + '\n')
```
这段代码会将`file.txt`文件中与`str_list`中任意一个字符串匹配的项找出来,并将结果存储在`match_result`中。如果`match_result`为空,说明没有匹配上,则将`str_list`中的字符串记录到`not_matched.txt`文件中。
相关问题
python删去字符串中与一个list中元素匹配的字符
可以使用Python中的字符串方法和列表推导式来实现删除字符串中与一个列表中元素匹配的字符。具体实现如下:
```python
str1 = "hello world"
lst1 = ['l', 'o']
result = ''.join([char for char in str1 if char not in lst1])
print(result)
```
输出结果为:
```
he wrd
```
解释一下代码逻辑:
- 首先定义一个字符串 `str1` 和一个列表 `lst1`,其中 `lst1` 存储了需要删除的字符;
- 使用列表推导式遍历字符串 `str1` 中的每一个字符,如果该字符不在列表 `lst1` 中,就将其添加到一个新列表中;
- 最后使用字符串的 `join()` 方法将新列表中的字符拼接成一个新的字符串。
这样就可以得到一个删除了字符串中与列表中元素匹配的字符的新字符串。
python2 将list中的每个字符串与当前路径path.properties文件每一行的开头进行模糊匹配,如果匹配上了,就记录properties文件这一行的内容
好的,首先需要读取path.properties文件的内容,可以使用Python内置的`open()`函数打开文件,然后使用`readlines()`方法将文件中的内容读取到一个列表中。代码示例如下:
```python
with open('path.properties', 'r') as f:
lines = f.readlines()
```
接下来,我们可以遍历列表中的每一行,使用`startswith()`方法判断该行是否以某个字符串开头,如果是,则将该行的内容记录下来。代码示例如下:
```python
import os
# 获取当前路径
cur_path = os.path.abspath(os.path.dirname(__file__))
# 读取path.properties文件内容
with open(os.path.join(cur_path, 'path.properties'), 'r') as f:
lines = f.readlines()
# 要匹配的字符串列表
str_list = ['str1', 'str2', 'str3']
# 记录匹配到的内容
matched_lines = []
# 遍历每一行,进行模糊匹配
for line in lines:
for s in str_list:
if line.startswith(s):
matched_lines.append(line)
break
```
这样,`matched_lines`列表中就存储了所有匹配到的行的内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)