打印txtfile和list中的行号?

2024-10-02 06:33:46 发布

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

我有这段代码,它打印了infile中的行号,也打印了words中的行号,我该怎么做才能只打印words旁边的txt文件的行号???在

d = {}
counter = 0
wrongwords = []
for line in infile:
infile = line.split()
wrongwords.extend(infile)
counter += 1
for word in infile:
    if word not in d:
        d[word] = [counter]
    if word in d:
        d[word].append(counter)

对于用错别字写的东西: 打印(stuff,d[stuff])

输出为:

^{pr2}$

Tags: 文件代码intxtforiflinecounter
1条回答
网友
1楼 · 发布于 2024-10-02 06:33:46

四件事:

  1. 您可以通过这样做来跟踪行号,而不是处理 自行反击:

    for line_no, word in enumerate(infile):
    
  2. 正如sateesh在上面指出的,您可能需要在 条件:

    if word not in d:
        d[word] = [counter]
    else:
        d[word].append(counter)
    
  3. 还请注意,上面的代码片段正是defaultdict的内容 用于:

    from collections import defaultdict
    d = defaultdict(list)
    

    然后在主循环中,可以去掉if..else部分:

    d[word].append(counter)
    
  4. 你为什么这么做?

而且,我真的不明白你应该如何决定什么是“错别字”。我假设您有一个名为wrongwords的集合,它包含错误的单词,这使得您的最终代码如下所示:

from collections import defaultdict
d = defaultdict(list)
wrongwords = set(["hello", "foo", "bar", "baz"])
for counter, line in enumerate(infile):
    infile = line.split()
    for word in infile:
        if word in wrongwords:
            d[word].append(counter)

相关问题 更多 >

    热门问题