【问题标题】:How do I search if a word exists in a file in python?如何在python的文件中搜索单词是否存在?
【发布时间】:2018-04-07 06:16:47
【问题描述】:

我有一个名为“dictionary.txt”的文件,其中包含按字母顺序排列的字典中的单词。

我想搜索某些单词是否在这本词典中。 谁能帮我编写可以打开这个文件的代码,然后我写一个单词作为输入,然后我收到一个输出,说明该单词是否在字典文件中?

这是我目前所拥有的:-

dicfile = open('dictionary.txt', 'r') 
word = input('enter a word: ') 
if word in dicfile: 
    print('true') 
else: 
    print('false')

【问题讨论】:

  • 很好的解释你能展示你的代码吗?
  • dicfile = open('dictionary.txt', 'r') word = input('enter a word: ') if word in dicfile: print('true') else: print('false ')
  • 我仍然是 python 的初学者,所以非常感谢任何帮助。

标签: python python-3.x file


【解决方案1】:
fd = open("abc.txt","r")    # open the file in read mode
file_contents = fd.read()   # read file contents
word = "hello"              # input word to be searched
if(word in file_contents):  # check if word is present or not
    print("word found")
else:
    print("word not found")
fd.close()                  # close the file

【讨论】:

    【解决方案2】:

    你差不多了,只是需要更多关于 python 文件处理的信息。

    dictionary.txt 文件:

    bac def ghij kl mano pqrstuv
    

    这是您修改后的代码代码

    dicfile = open('dictionary.txt', 'r') 
    file1 = dicfile.read()
    file1 = file1.split()
    
    word = input('enter a word: ') 
    if word in file1:
        print('true')
    else:
        print('false')
    

    输出:

    测试用例 1

    $ python3 test_9.py
    
    enter a word: bac
    true
    

    测试用例 2

    $ python3 test_9.py
    
    enter a word: anyword
    false
    

    【讨论】:

      【解决方案3】:
       def check_word(filename, word):
           with open(filename) as fin:
               if word in fin.read():
                    return True
               else:
                   return False
      

      【讨论】:

        【解决方案4】:

        假设您想在文件中找到x。你可以这样做:

        with open("textfile.txt") as openfile:
            for line in openfile:
                for part in line.split():
                    if "x" in part:
                        print part
                    else:
                        print false 
        

        `

        【讨论】:

          【解决方案5】:

          这是使用过程编程的一种方法

          dictionary = open('dictionary.txt', 'r')  #Only read
          
          word = input('Enter a word:\n)  #input typed on line below this
          
          if word in dictionary:
              print('{} is in the dictionary (True)'.format(word))
          else:
              print('{} is not in the dictionary (False)'.format(word))
          

          这是另一个:

          def in_file(filename, word):
              file = open(filename, 'r')
              if word in file:
                  return True
              else:
                  return False
          
          word = input("Enter a word:\n")
          in_file('dictionary.txt', word)
          

          对于不区分大小写的结果,您可以使用word.lower()。希望这会有所帮助。

          【讨论】:

            【解决方案6】:

            Stack Overflow 不是代码编写服务,我们只会在人们尝试做某事并卡住时尝试帮助他们,我不会给出确切的解决方案,但我会告诉你如何实现目标,休息是你的功课:

            @Srikar Appalaraju 的好回答

            #Sample 1 - elucidating each step but not memory efficient
            lines = []
            with open("C:\name\MyDocuments\numbers") as file:
                for line in file: 
                    line = line.strip() #or some other preprocessing
                    lines.append(line) #storing everything in memory!
            
            #Sample 2 - a more pythonic and idiomatic way but still not memory efficient
            with open("C:\name\MyDocuments\numbers") as file:
                lines = [line.strip() for line in file]
            
            #Sample 3 - a more pythonic way with efficient memory usage. Proper usage of with and file iterators. 
            with open("C:\name\MyDocuments\numbers") as file:
                for line in file:
                    line = line.strip() #preprocess line
                    doSomethingWithThisLine(line) #take action on line instead of storing in a list. more memory efficient at the cost of execution speed.
            

            例子:

            with open('dictionary.txt','r') as f:
                #for reading line by line
                for line in f:
            
                    print(line)
            
            
            
            
            
                #reading whole file once
                print(f.read())
            

            现在如何检查文件中的单词:

            使用python'in'运算符

            #checking word
            if 'some_word' in line:
                print(True)
            else:
                print(False)
            

            现在尝试一些东西,当你卡住时寻求帮助,而不是要求编写代码。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2015-01-31
              • 1970-01-01
              • 1970-01-01
              • 2019-11-16
              • 1970-01-01
              • 2015-12-17
              • 2013-09-17
              • 1970-01-01
              相关资源
              最近更新 更多