在特定条件下从TXT文件中过滤列表

发布于 2025-01-21 15:34:11 字数 167 浏览 0 评论 0原文

我需要在特定单词上过滤txt文件。以少于10个字母和具有重复字母的字母的字母结尾的单词应从TXT文件中过滤出来。然后,应将它们作为单词和单词数的列表返回。到目前为止我有这个

exclude = 'd'
f = open('nameofthefile.txt', 'r')

I need to filter a txt file on specific words. Words that end with 'd', that are less than 10 letters and words that have duplicate letters should be filtered out from the txt file. Then they should be returned as a list of words and number of words as a pair. So far I have this

exclude = 'd'
f = open('nameofthefile.txt', 'r')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梓梦 2025-01-28 15:34:11

这是我做的。

我不确定我会理解您所说的一切,但这是我所做的:

namefthefile.txt

abcd
abcdefghijk
0123456789d
aabbccdd

main.py:

def filtering(filename: str):
    f = open(filename,'r').read().split("\n")
    lst = []
    for e in f: # For elements in file
        if e[-1] == "d" and len(e) < 10 and sorted([*set(e)]) == sorted(e):
            lst += [e]
    return lst
    
print(filtering('nameofthefile.txt')) # ["abcd"]

您可以像:

def filtering(filename: str):
    f = open(filename,'r').read().split("\n")
    return [e for e in f if e[-1] == "d" and len(e) < 10 and sorted([*set(e)]) == sorted(e)]
    
print(filtering('nameofthefile.txt')) # ["abcd"]

如果最后一个字母为: D:

e[-1] == 'd'

如果单词小于10个字母:

len(e) < 10

如果该单词没有重复的字母

sorted([*set(e)]) == sorted(e)

Here is what I made.

I'm not sure I understood everything you said but here is what I made:

nameofthefile.txt:

abcd
abcdefghijk
0123456789d
aabbccdd

main.py:

def filtering(filename: str):
    f = open(filename,'r').read().split("\n")
    lst = []
    for e in f: # For elements in file
        if e[-1] == "d" and len(e) < 10 and sorted([*set(e)]) == sorted(e):
            lst += [e]
    return lst
    
print(filtering('nameofthefile.txt')) # ["abcd"]

You can refractor it like:

def filtering(filename: str):
    f = open(filename,'r').read().split("\n")
    return [e for e in f if e[-1] == "d" and len(e) < 10 and sorted([*set(e)]) == sorted(e)]
    
print(filtering('nameofthefile.txt')) # ["abcd"]

If the last letter is d:

e[-1] == 'd'

If the word is less than 10 letters:

len(e) < 10

If the word doesn't have duplicate letters

sorted([*set(e)]) == sorted(e)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文