1

Python学习者在这里。所以我有一个 wordlist.txt 文件,每行一个单词。我想过滤掉以特定字母开头和结尾的特定单词。但是在我的 wordlist.txt 中,单词是用它们的出现次数列出的。

例如:

food 312
freak 36
cucumber 1

这是我的代码

wordList = open("full.txt","r", encoding="utf-8")
word = wordList.read().splitlines()

for i in word:
    if i.startswith("h") and i.endswith("e"):
        print(i)

但是由于列表中的每个项目最后都有数字,我无法过滤正确的单词。我不知道如何省略这些数字。

4

2 回答 2

1

尝试使用空格作为分隔符来分割行,并使用第一个值[0],即你的情况下的单词

for i in word:
    if i.split(" ")[0].startswith("h") and i.split(" ")[0].endswith("e"):
        print(i.split(" ")[0])

或者你可以只执行一次拆分

for i in word:
    w = i.split(" ")[0]
    if w.startswith("h") and w.endswith("e"):
        print(w)

编辑:根据下面的评论,如果碰巧有两个空格或一个制表符作为字段分隔符,您可能希望不使用参数或 None 进行拆分。

w = i.split()[0]
于 2020-05-20T11:31:02.990 回答
0

尝试这个

str = "This must not b3 delet3d, but the number at the end yes 12345"
str = re.sub(" \d+", "", str)

str 将是 = "这一定不是 b3 delet3d,但末尾的数字是"

于 2020-05-20T11:35:10.630 回答