python - 编写一个程序从字符串中打印 haax

标签 python python-3.x

hapax 是一个在字符串中只出现一次的单词。我的代码可以工作。起初,它得到了第一个 hapax,然后,我更改了输入的字符串,它得到了最后一个,以及第一个 hapax,但没有得到第二个 hapax...这是我当前的代码

def hapax(stringz):
    w = ''
    l = stringz.split()
    for x in l:
        w = ''
        l.remove(x)
        for y in l:
            w += y
        if w.find(x) == -1:
            print(x)


hapax('yo i went jogging then yo i went joggin tuesday wednesday')

我得到的只是

then
wednesday

最佳答案

您可以使用 Counter 类快速完成此操作。

>>> s='yo i went jogging then yo i went joggin tuesday wednesday'
>>> from collections import Counter
>>> Counter(s.split())
Counter({'yo': 2, 'i': 2, 'went': 2, 'joggin': 1, 'then': 1, 'tuesday': 1, 'wednesday': 1, 'jogging': 1})

然后只需迭代返回的字典,查找计数为 1 的单词

>>> c=Counter(s.split())
>>> for w in c:
...     if c[w] == 1:
...         print w
... 
joggin
then
tuesday
wednesday
jogging
>>> 

您会注意到该字符串中实际上有五个 hapaxes:joggin、then、tuesday、wednesday 和 jogging。

您可能需要额外的逻辑来确定“慢跑”和“慢跑”是否是不同的词。您还需要确定标点符号是否重要(如果不重要则将其删除)。这完全取决于您的问题陈述的精细要求。

关于你的原始代码,我不确定你想用这个循环来完成什么:

for y in l:
    w += y

它只是将所有单词连接成一个不带空格的字符串。因此,如果 l 是 ['the','cat','sat','on','the','mat']w 将是 'thecatsatonthemat' 这可能会导致您的比赛出现问题。如果原始字符串包含“I may be that Maybe you are right”,则单词“may be”将连接到“maybe”,find 将找到它们。

关于python - 编写一个程序从字符串中打印 haax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29211492/

相关文章:

android - 使用 Appium 在真正的 Android 设备上以隐身模式打开 Chrome

python - 如何捕获使用 python subprocess.checkout() 调用调用的 C++ 程序中发生的异常?

python - 绘制几个极坐标图的散点图

python - 如何加快pandas数据框中列的匹配速度

Python在postgresql表中查找带有单引号的字符串

python - tkinter 在窗口关闭之前不会打印

python - 无法从某些 html 元素中获取文本的特定部分

python - 如何知道函数返回类型和参数类型?

python - 无法直接应用网格网格来创建 Surfaceplot

python - 找不到模块错误 : No module named 'src'