python - 使用 RegEx 查找并打印土耳其语中的复数单词

标签 python regex python-3.x

我对Python还很陌生。在代码中,我读取了一个文本文件作为输入,并将在此文本文件中读取的每一行作为元素放入列表中。

我正在尝试使用 RegEx 编写代码来查找和打印复数单词。在土耳其语中,复数单词是“-ler”或“-lar”后缀。

我的代码如下:

import re

f = open('C:/Users/ENE/Desktop/CSE & Kodlar/nlp/utf8textfile.txt', encoding='utf-8-sig', errors='ignore')


with f as file:
    list = file.readlines()
list = [x.strip() for x in list]

print(list)

total = 0
for i in list:
    total += len(i)
ave_size = float(total) / float(len(list))
print("Average word length = " + str(ave_size))

#p = re.compile('.*l[ae]r.*')

for element in list:
    m = re.findall(".*l[ae]r.*", element)
    if m:
        print(m)

输出为

list = ['Aliler geldiler', 'Selam olsun sana', 'Merhabalar', 'Java kitabı nerede']

for循环: [‘阿利尔·盖尔迪勒’] ['梅尔哈巴拉尔']

我正在尝试逐字打印,例如 ['Aliler']、['geldiler'] 和 ['Merhabalar']。我怎样才能做到这一点?

最佳答案

您可以使用 \w*l[ea]r\b 正则表达式找到所有以 larler 结尾的单词:

results = re.findall(r'\w*l[ea]r\b', s)

请参阅regex demo 。在 Python 3.x 中,\b 字边界默认支持 Unicode,在 Python 2.x 中,我建议添加 re.U 标志。

这里,s可以是整行,甚至是整个文档。

详细信息

  • \w* - 0+ 个字母、数字和 _ (在 Python 3.x 中,它将匹配所有 Unicode 字母、数字或 _ code>,您可以使用 [^\W\d_]* 仅匹配字母)
  • l - l 字母
  • [ea] - ea
  • r - r 字母
  • \b - 字边界(请注意 r'..' 表示法,用于避免双重转义 \b 以使引擎将其解析为单词边界)。

关于python - 使用 RegEx 查找并打印土耳其语中的复数单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49617624/

相关文章:

python - 如何将形状多边形转换为多边形

python - 如何使用 python 正则表达式从日志文件中查找所有回溯?

python - 使用 4300 万行文本文件中的计数创建字典的更简单方法是什么?

python-3.x - Django NoReverseMatch : Reverse for ‘entry’ not found. ‘login’ 不是有效的 View 函数或模式

python - 对 pandas 列执行条件操作

python - 在 Linux 上使用 Python 获取文件创建时间

python - 'int' 对象没有属性 '__getitem__'(再次)

arrays - 如何过滤数组中既匹配某个模式又不匹配第二个模式的元素?

javascript - 选择字符串中第 n 个数字和第 n 个数字正则表达式之间的所有字符

python - Pandas reshape 柱形