【问题标题】:Python - Accessing items inside a list from text filePython - 从文本文件访问列表中的项目
【发布时间】:2018-11-23 14:21:11
【问题描述】:

我正在尝试对列表中的项目应用验证。我已经设法打开它,但正在努力比较这两个词是否是字谜。

这是我在终端中的结果。

anagram:  ['word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff']

Anagram

在这个示例中,很明显我对两个相同的变量 A、B 做错了,但不知道该怎么做。

word1 = open('a.txt', 'r').read().split()
word2 = open('a.txt', 'r').read().split()
count = {}
validation = True
if len(a) == len(b):
    for i in range(len(a)):
        if a[i] in count:
            count[a[i]] += 1
        else:
            count[a[i]] = 1  
        if b[i] in count:
            count[b[i]] += 1
        else:
            count[b[i]] = 1     
    for i in count:
        if count[i] % 2 == 0:
            validation = "Anagram"
        else:
            validation = "Not Anagram"
            break
else:
    validation = "Not Anagram"            
print(validation)

我到底在做什么?

我想在终端中实现这个。

anagram:  ['word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff']

anagram, not anagram, anagram, not anagram, anagram, not anagram, anagram, not anagram

【问题讨论】:

  • 也许提供您想要达到的预期结果。
  • 完成。见上文^

标签: python list file


【解决方案1】:

您可以尝试使用sets 来实现:

anagram = ['word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff']
for elem in anagram:
    items = elem.split(",")
    firstLetters = set(items[0])
    secondLetters = set(items[1])
    if firstLetters == secondLetters:
        print("Anagram")
    else:
        print("Not anagram")

输出:

Anagram
Not anagram
Anagram
Not anagram
Anagram
Not anagram
Anagram
Not anagram

编辑:以下是从文件中读取它们并进行比较的方法:

with open("anagram.txt","r") as inFile:
    words = [line for line in inFile]
    words = words[0].strip().split(",")
    first = []
    second = []
    for i in range(len(words)):
        if i%2 == 0:
            first.append(words[i])
        else:
            second.append(words[i])
    for f,s in zip(first,second):
        if set(f) == set(s):
            print("Anagram")
        else:
            print("Not anagram")

【讨论】:

  • 正在从文本文件中读取数据集。这就是我觉得困难的地方。
  • 那么你如何获得anagram 的元素呢?如果您可以为这两个文件提供一些示例数据,那么我可以重现您的问题。
  • 我通过在文本编辑器中打开文件来检索它们。代码读取文本文件中的列表: a = open('anagram.txt', 'r').read().split()
  • 对不起。我有一个单独的部分打印出列表: anagramlist = open('anagram.txt', 'r').read().split() print(anagramlist)
  • 如您所见,我复制了(我知道这是错误的),但不知道如何正确执行此操作。
猜你喜欢
  • 2019-06-25
  • 2018-04-03
  • 1970-01-01
  • 2019-11-11
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多