How to Open a File and Search for a Word

JavaScript - Open file, search for string and print the next word

You can split the content by a whitespace separator into an array of strings, roughly "words", then traverse the array and when the string (word) you are looking for occurs store the next array item:

var wanted = 'Apples';
var words = reader.responseText.split(/\s/);
var found = [];
words.forEach(function (word, index) {
// if we've got the match and the next item exists (we're not at the end of the array)
if (word === wanted && words[index + 1])
// push the next item (word) to the "wanted" array
found.push(words[index + 1]);
});
// join the results with line break elements and stuff them to el
document.getElementById('test').innerHTML = found.join('<br/>');

If you need to search for more than one wanted word, use array & indexOf:

var wanted = ['Apples', 'Onions'];
// ...
if (wanted.indexOf(word) !== -1 && words[index + 1])

(indexOf returns -1 if the element is not found.)

You example has more issues, the biggest of which I'd say is the reader scattered through several functions, it's generally better to keep it on one place and pass just the received content to the "business logic" function (inside the onreadystatechange callback), so the updated example:

<button onclick="loadFile()">Load file</button>
<div id="test"></div>

<script>
function loadFile() {
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');
reader.open('get', '/log-file.txt', true);
reader.onreadystatechange = function () {
if (reader.readyState == 4 && reader.status == 200) {
displayContents(reader.responseText);
}
};
reader.send();
}

function displayContents(content) {
var wanted = 'Apples';
var words = content.split(/\s/);
var found = [];
words.forEach(function (word, index) {
// if we've got the match and the next item exists (we're not at the end of the array)
if (word === wanted && words[index + 1]) {
// push the next item (word) to the "wanted" array
found.push(words[index + 1]);
}
});
// join the results with line break elements and stuff them to el
console.log('found:', found);
var el = document.getElementById('test');
el.innerHTML = found.length ? found.join('<br/>') : 'nothing found';
}
</script>

How to open a file in python, search for a word ignoring case, print success of word is found?

You could try:

word = input("Word to look for: ")
word_lower = word.lower()

with open('book.txt', 'r') as fh:
data = fh.read().lower()
if word_lower in data:
print(word,"was found in the book.")
else:
print(word,"was not found in the book.")

I just forced both word and data (file's content) to lowercase .lower() so it becoms non-case sensitive.

I didn't update word directly but stored lowered string in another variable (word_lower) to allow you to print exactly what user inputed.

Taking words that I have in a list and searching for them within a Text File and getting a count for each word

To count the number of occurrences of a specific word in a text file, read the content of text file to a string and use String.count() function with the word passed as argument to the count() function.

Syntax:

n = String.count(word)

where word is the string, and count() returns the number of occurrences of word in this String.

So you can read the file and make use of count() method.

#get file object reference to the file
with open("file.txt", "r") as file:
#read content of file to string
data = file.read()

words = ['apple', 'orange']

for word in words:
print('{} occurred {} times.'.format(word, data.count(word)))

Hopefully, this should work fine.

Note:
You can even loop through each and every word and increment the counter. But using a high-level programming language like Python, it would be beneficial to make use of such built-in methods.

Python: How can i search for a whole word in a .txt file?

Try this i have updated my answer.

import mmap
import re
status = False
username = input("username: ")
names_file = open("names_file.txt", "a")

paste = bytes(username, 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
for f in file:
f = f.strip()
if f == paste:
print("true")
status = True
if status == False:
names_file.write("\n" + username)
print(username + " got added to the list")

names_file.close()

How to search for a string in text files?

The reason why you always got True has already been given, so I'll just offer another suggestion:

If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):

with open('example.txt') as f:
if 'blabla' in f.read():
print("true")

Another trick: you can alleviate the possible memory problems by using mmap.mmap() to create a "string-like" object that uses the underlying file (instead of reading the whole file in memory):

import mmap

with open('example.txt') as f:
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find('blabla') != -1:
print('true')

NOTE: in python 3, mmaps behave like bytearray objects rather than strings, so the subsequence you look for with find() has to be a bytes object rather than a string as well, eg. s.find(b'blabla'):

#!/usr/bin/env python3
import mmap

with open('example.txt', 'rb', 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(b'blabla') != -1:
print('true')

You could also use regular expressions on mmap e.g., case-insensitive search: if re.search(br'(?i)blabla', s):



Related Topics



Leave a reply



Submit