无法在python中的re.findall中使用字符串中的单词

2024-09-27 04:20:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从用户那里获取单词输入,并从一个文本文件中找到这些单词,在这个文本文件中我有许多其他单词。有些词在重复,我也希望它们以同样的方式重复。我在Anaconda Spyder中使用“re”来运行我的代码。我可以成功地做到这一点,并获得与搜索词的输出文本文件。但为此,我在代码中定义了单词。我不明白如何为这个操作输入一个单词。输入来自GUI复选框选择。所以我需要将输入的单词保存在一个字符串中并使用它。我需要使用“|”运算符。这是我的密码

import re 
from pathlib import Path

#words are=== mango, cat, dog, tiger, three, hat, hot, sweden, kth

wordset = Path('words.txt').read_text()
#wordset = wordset.replace('\n', '')

# lst = ['kth','cat','tiger']
    
#####here in the words_record section, it should get the key-words from the user's input or another code's output result. so basically the words are going to a string. but I am unable to use string value here. The user will give both single word input and multiple word input.

words_record = 'kth|cat|tiger'

#XY = re.findall(words_record, wordset)
XY = re.findall(words_record, wordset, flags=re.IGNORECASE)

# print(XY)

with open('filtered_list.txt', 'w') as filehandle: ###save output in textfile
    for listitem in XY:
        filehandle.write('%s\n' % listitem)

Tags: the代码inimportreinputrecord单词
1条回答
网友
1楼 · 发布于 2024-09-27 04:20:55

如果我运行这个代码

import re 
wordset = "mango, cat, dog, tiger, three, hat, hot, sweden, kth"
words_record = 'kth|cat|tiger'
XY = re.findall(words_record, wordset, flags=re.IGNORECASE)
print(XY) #=> ["cat", "tiger", "kth"]

正如预期的那样,它工作得非常好

要获取正则表达式字符串,可以使用

raw_user_input_string.replace(' ','|').replace("\n",'|')

我不确定我是否理解正确,但我认为你们在寻求实现单/多行用户输入的方法

Python中的多行用户输入可以通过以下方式实现:

lines = []
while True:
    line = input()
    if line:
        lines.append(line)
    else:
        break
text = '\n'.join(lines)

ZdaR的答复https://stackoverflow.com/a/30239138/8106583

如果完成,用户只需提交一个空行。 变量text则包含一个或多行字符串

如果您想要这个特殊格式的关键字"kth|cat|tiger",那么只需使用类似

text.replace("\n",'|').replace(' ','|')

相关问题 更多 >

    热门问题